简体   繁体   English

如何在javascript中单击操作时为DOM中新添加的元素编写回调?

[英]How to write callback for newly added element in DOM upon click action in javascript?

I have a button which adds new element to DOM.我有一个向 DOM 添加新元素的按钮。 Now I want to write event listner for click on this new Element.现在我想编写事件监听器来点击这个新元素。 But not able to do so because when page loads this element will not be in DOM.但不能这样做,因为当页面加载时,这个元素不会在 DOM 中。 The code I have tried so far is到目前为止我尝试过的代码是

    const initButton = document.querySelector(".wS .amr .amn .ams");
    initButton.click() // this will add new element in DOM which will be async action

    // now I want to perform following on newly added element
    
    document.querySelector(".fX.aXjCH").setAttribute("style", "display:block");
    document.querySelector(".aB.gQ.pE").click();

I need some callback mechanism so that I can execute the later code once the DOM is updated with new component.我需要一些回调机制,以便在使用新组件更新 DOM 后我可以执行后面的代码。 How can I achieve this?我怎样才能做到这一点? how can I make assure the DOM is updated?如何确保 DOM 已更新? or is there any way I can write callback for the first click()?或者有什么办法可以为第一次点击()编写回调?

  1. Have the script tag just before the end body tag在结束正文标签之前有脚本标签
  2. Add readystatechange event like this -像这样添加readystatechange事件 -
  3. after the append yo can access the newly added markup.在追加之后你可以访问新添加的标记。

Note: this kind of appending child using in .innerHTML is not safe if the markup is coming from say a Database and can cause XSS unless we sanitize the str .注意:如果标记来自数据库,则在.innerHTML使用这种附加子项是不安全的,除非我们清理str否则可能导致 XSS。

 <body> <ul id="ul_o"> <button class='wS amr amn ams'>WS </button> <div class='container'> </div> </ul> <script type='text/javascript'> document.onreadystatechange = function () { if (document.readyState === "interactive") { const initButton = document.querySelector(".wS.amr.amn.ams"); const container = document.querySelector(".container"); initButton.addEventListener('click', function(){ var str = '<p>something here</p>'; var temp = document.createElement('div'); temp.innerHTML = str; container.appendChild(temp); const span = document.querySelector("p"); console.log(span); }); } } </script> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM