我的理解是,我通常应该避免在HTML中使用onclick,因为最好将HTML结构和JS逻辑分开。然而,在本例中,我有一个应用程序,用户可以在其中搜索记录,结果显示在div中,该div是使用AJAX从php文件动态生成的。在每个div中都有一个按钮,当单击该按钮时,必须执行一个JS函数,函数参数是记录的唯一id。
我的观点是:如何选择一个使用普通JS动态创建的按钮,因为它在加载JS时并不存在?
发布于 2020-08-26 02:09:31
不是将click处理程序添加到按钮,而是将其附加到按钮放置位置的父元素。然后,在单击处理程序中使用e.target,您可以引用所单击的按钮。
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>";<div>
</div>
发布于 2020-08-26 02:32:44
您可以使用事件冒泡的概念。
示例:
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);https://stackoverflow.com/questions/63584687
复制相似问题