我正在开发一个聊天应用程序,当我尝试向聊天室列表中添加新元素,查看它们并与之交互而不重新加载页面时,就会出现问题。
我正在使用JavaScript将HTML元素添加到列表中。
然后,我尝试查询列表中的SelectSelectorAll元素。
可以选择在页面加载时从服务器加载的元素。
但是似乎没有选择使用JavaScript新建的元素。
这里是我尝试选择元素的方法,单击这些元素时,对每个元素执行一些代码:
document.querySelectorAll('.select-room').forEach(p => {
p.onclick = () => { <my code here> })
已经在列表中的元素被选中的很好,我的代码可以执行。
但是当我使用JavaScript添加新元素时。即使它的HTML看起来与其他现有元素的HTML相同(包括选择它的类),结果还是我只能在重新加载页面后才能选择它们。
有没有一种方法可以监听对DOM所做的更改,以便在使用JavaScript添加具有相同类的新元素之后,将像其他元素一样选择它们,而不必重新加载页面。
这里是我的问题的Minimal, Complete, Reproducible Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>mcr problem</title>
<script>
document.addEventListener("DOMContentLoaded", () => {
// Clicking element in the list shows an alert.
document.querySelectorAll(".clickable").forEach(li => {
li.onclick = () => {alert("interaction!")};
});
// Clicking on button adds new element to the list
document.querySelector("#add-btn").onclick = () => {
newLi = document.createElement("li");
newLi.classList.add("clickable");
newLi.innerHTML = "New Item";
document.querySelector("#parent-list").append(newLi);
};
});
</script>
</head>
<body>
<h1>List of items</h1>
<button id="add-btn">Add</button>
<ul id="parent-list">
<li class="clickable" id="post-1">Item 1</li>
<li class="clickable" id="post-2">Item 2</li>
<li class="clickable" id="post-3">Item 3</li>
</ul>
</body>
</html>
[为什么没有收到警报DOMContentLoaded
当DOM树形式(即脚本正在加载)时触发此事件。在加载所有资源(例如图像,CSS和JavaScript)之前,脚本开始运行。您可以将此事件附加到窗口或文档对象当时查询选择器只有3个类别为.clickable
的节点,因此它仅适用于这3个元素。在javascript DOMNodeInserted
中当脚本使用appendChild(),replaceChild(),insertBefore()等在DOM树中插入新节点时,它将触发。
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll(".clickable").forEach((li) => {
li.onclick = () => commonAlertMethod();
});
// Clicking on button adds new elemnt to the list
document.querySelector("#add-btn").onclick = () => {
newLi = document.createElement("li");
newLi.classList.add("clickable");
newLi.innerHTML = "New Item";
document.querySelector("#parent-list").append(newLi);
};
});
document.addEventListener("DOMNodeInserted", () => {
// Clicking element in the list shows an alert.
document.querySelectorAll(".clickable").forEach((li) => {
li.onclick = () => commonAlertMethod();
});
});
function commonAlertMethod() {
alert("interaction!");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>List of items</h1>
<button id="add-btn">Add</button>
<ul id="parent-list">
<li class="clickable" id="post-1">Item 1</li>
<li class="clickable" id="post-2">Item 2</li>
<li class="clickable" id="post-3">Item 3</li>
</ul>
</body>
</html>