这是带有自定义Web组件的HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Advanced ToDo App with Web Components</title>
</head>
<body>
<todo-item todo="Walk the dog" data-id="1"></todo-item>
<script src="../static/listItems.js"></script>
</body>
</html>
这是我在其中设置组件的JS文件。
const template = document.createElement("template");
template.innerHTML = `<style>
h4 {
color: white;
font-size: 14px;
display: block;
padding: 10px 5px;
background: orange;
}
</style>
<div class="todo-item">
<h4></h4>
</div>
`;
class TodoItem extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
}
connectedCallback() {
this.shadowRoot
.querySelector(".todo-item")
.addEventListener("click", () => {
console.log(this.getAttribute("data-id"));
});
}
}
window.customElements.define("todo-item", TodoItem);
// Über Daten iterieren
const body = document.querySelector("body");
const dummydata = [
{ id: 1, description: "Walk the dog" },
{ id: 2, description: "Play football" }
];
for (item of dummydata) {
console.log(item.description);
todoItem = document.createElement("todo-item");
todoItem.setAttribute("todo", item.description); # Does not work!
todoItem.setAttribute("data-id", item.id);
body.appendChild(todoItem);
}
HTML中的组件工作正常,但是当我尝试使用JavaScript动态创建它们时,设置属性似乎不起作用。不会显示“待办事项”文本。设置此“ todo”属性无效吗?
注意-必须在connectedCallBack
函数中设置属性。进行此操作之前,属性值将为null
connectedCallback() {
this.shadowRoot
.querySelector(".todo-item")
.addEventListener("click", () => {
console.log(this.getAttribute("data-id"));
});
this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
}