【发布时间】:2021-12-28 17:39:24
【问题描述】:
代码来自这个页面https://usefulangle.com/post/362/custom-elements 它使用影子 DOM 构建自定义 html 表单元素。
我在“Inspect”中打开代码,看到了这个错误。
class InputPlusMinus extends HTMLElement {
constructor() {
super();
let template = document.querySelector('#input-plus-minus-template').content;
this.attachShadow({
mode: 'open'
}).appendChild(template.cloneNode(true));
let add_button = this.shadowRoot.querySelector("#add");
let subtract_button = this.shadowRoot.querySelector("#subtract");
let count_textbox = this.shadowRoot.querySelector("#count");
this.setAttribute('value', '1');
add_button.addEventListener('click', () => {
let current = parseInt(count_textbox.value, 10);
count_textbox.value = current + 1;
this.setAttribute('value', count_textbox.value);
});
subtract_button.addEventListener('click', () => {
let current = parseInt(count_textbox.value, 10);
if (current > 1) {
count_textbox.value = current - 1;
this.setAttribute('value', count_textbox.value);
}
});
}
}
customElements.define('input-plus-minus', InputPlusMinus);
<template id="input-plus-minus-template">
<style>
button {
width: 25%;
/* other CSS */
}
input {
width: 50%;
/* other CSS */
}
</style>
<div id="container">
<button id="subtract">-</button>
<input type="text" id="count" value="1" readonly />
<button id="add">+</button>
</div>
</template>
<!-- custom element being used -->
<input-plus-minus id="sample"></input-plus-minus>
【问题讨论】:
-
什么浏览器和版本?
-
Microsoft Edge 版本 95.0.1020.53(官方版本)(64 位)
-
@mplungjan 当我在这里运行编辑后的代码 sn-p 时,它会显示结果。但是,当我将代码复制到 .html 文件并在浏览器中打开它时,它只显示文本
-
@Gabriele Petrioli 成功了。非常感谢!
标签: javascript html shadow-dom