我正在探索web组件的自定义HTML元素,我遇到了一个向自定义元素添加自定义属性的问题:我在标记中设置的任何值都不会生效。对于像这样的简单元素,它应该显示在“For text”属性中提供的文本,它总是显示默认值。
<test-flag flagtext="my text"></test-flag>
完整的JSBin示例是here。
JSBin使用聚合物库(因为这是我唯一能放进去的东西)。我一般使用webcomponents.js,结果是一样的。在Chrome49和Firefox45中都有相同的结果。控制台或调试器中未显示错误。
我在网上找到的每个样本都有类似的代码,但我尝试了不同的版本,它总是拒绝更新。我甚至将一些示例复制到JSBin中,但它们也不起作用。
会出什么问题呢?我知道这是一种实验性技术,但这种不起作用的一致性仍然令人惊讶。这个标准已经被抛弃了吗?(我看到最新的2016年4月W3C自定义元素草案已经完全改变了它的方法。)
当我定义"attributeChangedCallback“函数时,它不会触发。我可以很容易地通过Javascript修改属性,这不是问题。
但是为什么我不能在标记中指定属性,因为我应该这样做?
编辑-完整的代码
请注意,对于HTML导入,您需要将这些文件放入单独的文件中,并且您需要“webcomponents lite.js”库。
主文件
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
test-flag
{
border: 1px solid blue;
}
</style>
</head>
<body>
<script src="lib/webcomponents-lite.min.js"></script>
<link rel="import" href="test-flag.html">
Here is the custom test-flag component:
<p>
<test-flag flagtext="my text"></test-flag>
</body>
</html>
测试文件:-Flag.html
<template>
<style>
</style>
Content:
<div id="testflagID">
</div>
</template>
<script>
(function() {
var _currentScript = (document._currentScript || document.currentScript);
var importDoc = _currentScript.ownerDocument;
var customPrototype = Object.create(HTMLElement.prototype);
Object.defineProperty(customPrototype, 'flagtext', {value: '(default)', writable: true});
document.registerElement('test-flag', {prototype: customPrototype});
customPrototype.createdCallback = function()
{
var template = importDoc.querySelector('template');
var clone = document.importNode(template.content, true);
var idx = clone.querySelector("#testflagID");
idx.textContent = this.flagtext;
var root = this;
var createdElement = root.appendChild(clone);
};
})();
</script>
https://stackoverflow.com/questions/37253002
复制相似问题