簡體   English   中英

如何使用 javascript 查詢添加到 DOM 的 SelectorAll 元素?

[英]How to querySelectorAll elements added to the DOM with javascript?

我正在開發一個聊天應用程序,當我嘗試將新元素添加到聊天室列表、查看它們並與它們交互而不重新加載頁面時,我的問題就出現了。

我將 HTML 元素添加到具有 JavaScript 的列表中。

然后我嘗試查詢列表中的SelectorAll 元素。

可以選擇在頁面加載時從服務器加載的元素。

但是新創建的帶有 JavaScript 的元素似乎沒有被選中。

這是我如何嘗試 select 我的元素,並在單擊時為每個元素執行一些代碼:

 document.querySelectorAll('.select-room').forEach(p => {
        p.onclick = () => { <my code here> })

已經在列表中的元素被選中就好了,我的代碼執行得很好。

但是當我用 JavaScript 添加一個新元素時。 Even though the HTML of it looks just the same as the HTML of other existing elements, including the class by which it gets selected, the result is I can only select those after reloading the page.

有沒有辦法我可以監聽對 DOM 所做的更改,以便在使用 JavaScript 添加具有相同 class 的新元素后,它們將像其他元素一樣被選中,而無需重新加載頁面?

這是我的問題的最小,完整,可重現的示例

<!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 樹 forms 即腳本正在加載時觸發。 腳本在圖像、CSS 和 JavaScript 等所有資源加載之前開始運行。 您可以將此事件附加到 window 或文檔對象
並且當時查詢選擇器只有 class .clickable的 3 個節點,因此它僅適用於這 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM