Using functions defined within web component(使用Web组件中定义的函数)
问题描述
我构建了我的Web组件DataUint,并为其分配了一个标记<data-uint>,如下所示:
class DataUint extends HTMLElement
{
...
set value(x) { ... }
...
}
customElements.define("data-uint", DataUint);
创建和访问这样的组件时:
x = document.createElement('data-uint');
x.value = 10;
对value的调用实际上调用了setter方法并执行其函数。
但是,当我在html代码中内置组件时:
<body>
<data-uint id='num'></data-uint>
</body>
并尝试这样访问/使用它:
x = body.children[0];
x.value = 10;
对value的调用为x引用的元素设置了一个新属性,但从不调用Web组件的setter方法。
然而,x引用了页面上的正确元素(我的组件),我通过调用其他标准元素方法进行了验证。此访问方法似乎正在返回忽略专门化的泛型Element。
问题:
我想我在这里遗漏了一些基本概念。如何通过允许我使用其成员函数的方式从JavaScript访问html定义的组件?
推荐答案
您可能正在定义组件之前执行x = body.children[0]; x.value = 10;。还要注意的是,除非您在代码运行之前声明了一个局部变量body,否则body将是undefined,您的意思可能是使用const x = document.body.children[0];。
添加此行代码:
const x = document.body.children[0];
console.log(x.constructor.name);
x.value = 10;
如果得到HTMLElement,则说明您的组件当时尚未定义。如果尚未定义,则没有要执行的setter。
若要检查,您还可以执行console.log(x.matches(':defined'));。
若要解决此问题,请将代码包装在DOMContentLoaded侦听器中,或者等待组件定义完成:
customElements
.whenDefined('data-uint')
.then((promise) => {
const x = document.body.children[0];
console.log(x.constructor.name);
x.value = 10;
});
这篇关于使用Web组件中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用Web组件中定义的函数
基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
