当我像
一样直接写时<li onclick='document.location.href = "../?module"; return false'>
<h3>title</h3>
<p><a href="#delete">delete</a></p>
</li>
我可以单击链接的li元素内的删除链接,但是当我动态添加元素时,就像
var li = document.createElement("li");
li.onclick = function() {
document.location.href = "../?module";
return false;
}
li.innerHTML = '<h3>title</h3><p><a href="#delete">delete</a</p>';
var placeholder = document.getElementById("placeholder");
placeholder.insertBefore(li, placeholder.childNodes[0]);
我无法再单击删除链接。该如何解决?
答案 0 :(得分:0)
这是您想要的吗?评论中的解释
var li = document.createElement("li");
li.onclick = function() {
alert("li clicked");
return false;
}
li.innerHTML = '<h3>title</h3>'; // remove your p tag and a tag
let p = document.createElement("p"); // create p tag dynamically
let atag = document.createElement("a"); // create a tag dunamically
atag.setAttribute("href", "#delete"); // set the href attribute
atag.innerHTML = "delete" // set the inside html of a tag
atag.onclick = function() { // add a click handler to your a tag
alert("link clicked");
return false;
}
p.appendChild(atag); // append that a tag to p tag
li.appendChild(p); // append that p tag with the a tag inside
var placeholder = document.getElementById("placeholder");
placeholder.insertBefore(li, placeholder.childNodes[0]);
<div id="placeholder">
</div>