简体   繁体   中英

set onclick attribute in Javascript

When I run this Javascript code

var anchor = document.createElement("a");
anchor.style = "cursor:pointer;color:blue;";
 anchor.onclick = "this.parentNode.parentNode.removeChild(this.parentNode);";
 anchor.innerHTML = "remove";
 div.appendChild(anchor);

My anchor is created as <a style="cursor: pointer; color: blue;">remove</a> The onclick attribute is missing and the onclick function does not work.

Can I fix it?

You are setting it to a string and it does not actually set the attribute. Use a closure.

anchor.onclick = function() { this.parentNode.parentNode.removeChild(this.parentNode); };

ideally you would be using addEventListener

anchor.addEventListener("click", function(){ this.parentNode.parentNode.removeChild(this.parentNode); }, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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