首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何避免在动态生成的HTML元素(vanilla js)上使用onClick

如何避免在动态生成的HTML元素(vanilla js)上使用onClick
EN

Stack Overflow用户
提问于 2020-08-26 02:02:09
回答 2查看 162关注 0票数 0

我的理解是,我通常应该避免在HTML中使用onclick,因为最好将HTML结构和JS逻辑分开。然而,在本例中,我有一个应用程序,用户可以在其中搜索记录,结果显示在div中,该div是使用AJAX从php文件动态生成的。在每个div中都有一个按钮,当单击该按钮时,必须执行一个JS函数,函数参数是记录的唯一id。

我的观点是:如何选择一个使用普通JS动态创建的按钮,因为它在加载JS时并不存在?

EN

回答 2

Stack Overflow用户

发布于 2020-08-26 02:09:31

不是将click处理程序添加到按钮,而是将其附加到按钮放置位置的父元素。然后,在单击处理程序中使用e.target,您可以引用所单击的按钮。

代码语言:javascript
复制
var div = document.querySelector("div");

div.addEventListener("click",function(e){
    console.log(e.target.getAttribute("id"))
});

div.innerHTML = "<button id='test' type='button'>Test</button>";
代码语言:javascript
复制
<div>
</div>

票数 0
EN

Stack Overflow用户

发布于 2020-08-26 02:32:44

您可以使用事件冒泡的概念。

示例:

代码语言:javascript
复制
addDiv = document.querySelector("#addDiv");
list = document.querySelector(".list");
//as an example the ID is this counter
let id = 1;
addDiv.addEventListener("click", () => {
    //this is a callback function that is going to add a new item to the DOM.
    //in your case this is being implemented in php.
    list.innerHTML += `<br><div id="${id}"><button>Click me to see my ID</button></div> <br>`;
    id++; //meaning id = id + 1
});

//now the answer of your question:

const getTheID = (e) => {
    //this function will be called (invoked) as soon as one of the elements inside the ".list" div has been clicked
    e = e || window.event; 
    // "e" is the event that happened, it is an object that have lots of other objects, you can use "console.log(e);" to see what is "e", I've added the || (meaning OR) window.event to
    //make sure that I'll catch the event, you can just rely on the e argument that is being passed by the browser automatically, but the better implementation is to add || window.event
    target = e.target || e.srcElement; 
    // e.target and e.srcElement are the same thing, but I usually e.srcElement to make sure that the safari browser users will have my application working with them.
    //the e.target or e.srcElement is the HTML element that has been clicked, you can see that by "console.log(target);".
    target = target.parentNode;
    console.log(target);
    //this is what's called event bubbling, this code target.parentNode will move up inside the DOM to the parent of the clicked element, so from <button> to <div id="?"> Now we can see the parent element of the button.
    //if you need you can target.parentNode.parentNode.parentNode....etc as you need
    //see that in the console, use console.log(target); to see the output.
    const id = target.id;
    //here we're getting the ID of the element <div id="?">
    alert(id);
}

list.addEventListener("click", getTheID);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63584687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档