使用Google Chrome (v42)和原生webcomponents支持,我尝试使用自定义元素,其中自定义元素内容有时包含内联javascript标记。但是,每当遇到第一个<script>标记时,解析器似乎就会停止解析元素内容。我做错了什么?当初始化器(例如createdCallback)运行时,我如何确保我的自定义元素知道它的全部内容?
简化示例:
<html>
<body>
<script>
document.registerElement("element-count", {
prototype: Object.create(HTMLElement.prototype, {
createdCallback: {
value: function(){
this.appendChild(document.createTextNode(this.children.length));
}
}
})
})
</script>
<element-count>
<div>alpha</div>
<script></script><!-- this is here just to show that the parser stops -->
<div>beta</div>
</element-count>
</body>
</html>预期结果:
alpha
beta
3实际结果:
alpha
2
beta只要解析器遇到<script>元素,自定义元素的createdCallback就会运行。
我对自定义元素中的文档片段(在<element-count>中)没有太多的控制。实际版本的定制组件试图将任意的DOM片段包装到装饰精美的盒子中,并做一些其他的事情。
发布于 2015-08-11 16:00:30
你说得对,这是因为当调用createdCallback时,定制元素还没有被解析。
使用body.onload事件。或者将调用registerElement 的脚本放在自定义元素之后。
<html>
<body onload="register()">
<script>
function register()
{
document.registerElement( "element-count", {
prototype: Object.create( HTMLElement.prototype, {
createdCallback: {
value: function ()
{
this.appendChild( document.createTextNode( this.children.length ) );
}
}
} )
} )
}
</script>
<element-count id="c">
<script></script><!-- this is here just to show that the parser stops -->
<div>alpha</div>
<div>beta</div>
</element-count>
<button onclick="alert(c.children.length)">Recount</button>https://stackoverflow.com/questions/30135475
复制相似问题