javascript - customElements 在谷歌浏览器中不起作用
问题描述
我正在尝试在我的网站中使用一些自定义元素,并且在 Firefox 中它到目前为止效果很好。然而,在谷歌浏览器中,它只是默默地失败了——我的自定义元素的构造函数永远不会被调用,它也不会抛出错误。
假设这个最小的例子:
<!DOCTYPE html>
<html>
<head>
<script>
class MyElement extends HTMLDivElement {
constructor(){
super();
this.style.background = "#00ff00";
console.log("Created custom element!");
}
}
function addCustomElement(){
customElements.define("my-element",MyElement,{extends:"div"});
console.log("Added MyElement to custom element registry!");
}
</script>
</head>
<body onload="addCustomElement()">
<my-element style="display:block;width:100px;height:100px;background:#ff0000"></my-element>
</body>
</html>
我希望这会创建一个自定义元素类,并将DOM 中的MyElement
所有元素转换为该类的实例,一旦添加到自定义元素注册表,就会将原来的红色组件变成绿色。my-element
在 Firefox 中,这正是发生的情况,但在 google chrome 中,它保持红色。控制台表明该元素已添加到注册表中,但从未调用过它的构造函数。
我错过了什么吗?这是chrome的问题,还是我做错了什么?我怎样才能让它在那里工作?
解决方案
这里的工作示例
class MyElement extends HTMLElement {
constructor(){
super();
this.style.background = "#00ff00";
console.log("Created custom element!");
}
}
function addCustomElement(){
customElements.define("my-element", MyElement)
console.log("Added MyElement to custom element registry!");
}
// add call here, because onload did not work for me
addCustomElement()
https://jsfiddle.net/so98Lauz/1/
变化:
- 扩展 HTMLElement 而不是 HTMLDivElement
- 在js中调用
addCustomElement
函数以确保执行 - 从
{extends:"div"}
_customElements.define
推荐阅读
- fpga - 如何在没有 PS Logic 的情况下将数据从 FPGA 写入 DDR3 内存
- uwp - Win32应用程序关闭时如何关闭UWP App?
- r - 在ggplot中为多行着色
- node.js - @Exclude 装饰器不适用于 POST 方法,但适用于 GET 方法
- javascript - 点击输入时保持按钮焦点:Material-Ui
- python - 由于“未知标签类型'连续'”,逻辑回归不起作用?
- excel - 如何在 Excel 工作表中插入锁符号?
- elasticsearch - 如何在 Elasticsearch 中编写“where not exists”等效查询?
- javascript - React.js:如何比较来自 2 个数组对象的数据?
- google-cloud-sql - Cloud SQL 导入 API 问题,仅插入 2 609 397 条记录,其余记录已跳过