如何在innerHTML 中设置onclick 事件?

Del*_*ent 3 html javascript

我正在尝试使用innerHTML将一些数据插入到html页面中,如下所示

for(i = 0; i < data.length; i++){
var line = data[i].split("~");

nameslist.innerHTML += '<p onClick='+userclick(line[1])+'><strong>' + line[0] + ' </strong></p>';

}
Run Code Online (Sandbox Code Playgroud)

但是 onclick 事件在插入后立即自动触发,并且当我单击元素时它不会<p>触发

我如何正确使用innerhtml来添加带有onclick事件的ap元素并仅在用户单击时触发它?

小智 5

如果您愿意采取不同的方法,您可以向父节点添加事件侦听器,并让单击事件向上冒泡到父节点。

可以在此处找到示例: https: //davidwalsh.name/event-delegate

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");
    }
});
Run Code Online (Sandbox Code Playgroud)