2

我正在玩 W3C Web 组件。

我有一个主页,其中包括组件 A:

<!-- homepage.html -->
<link rel='import' href='a.html'>
<component-a></component-a>

在组件 AI 中包含另一个组件 B:

<!-- a.html -->
<link rel='import' href='b.html'>
<template>
  <component-b></component-b>
  <component-b></component-b>
</template>
<script>
  void function() {
    var currentDocument = document.currentScript.ownerDocument
    function getTemplate(selector) {
      return currentDocument.querySelector(selector).content.cloneNode(true)
    }

    var proto = Object.create(HTMLElement.prototype)
    proto.attachedCallback = function() {
      console.log('a')
      this.appendChild(getTemplate('template'))
    }
    document.registerElement('component-a', { prototype: proto })
  }()
</script>

B 的代码与 A 非常相似:

<!-- b.html -->
<template>
  <span>b</span>
</template>
<script>
  void function() {
    var currentDocument = document.currentScript.ownerDocument
    function getTemplate(selector) {
      return currentDocument.querySelector(selector).content.cloneNode(true)
    }

    var proto = Object.create(HTMLElement.prototype)
    proto.attachedCallback = function() {
      console.log('b')
      this.appendChild(getTemplate('template'))
    }
    document.registerElement('component-b', { prototype: proto })
  }()
</script>

奇怪的是,当页面加载时,我只能"a"在控制台中看到。我也期待"b"两倍。并且组件 B 并没有真正被解析。

更奇怪的是,如果我在控制台中运行以下代码:

document.querySelector('component-a').innerHTML += ''

它突然给了我两次"b"

这是一个屏幕截图:

在此处输入图像描述

4

1 回答 1

2

一位朋友给了我一个解决方案,使用document.importNode而不是cloneNode

function getTemplate(selector) {
  // return currentDocument.querySelector(selector).content.cloneNode(true)
  return document.importNode(currentDocument.querySelector(selector).content, true)
}

而且效果很好。

于 2015-05-30T01:50:29.697 回答