简体   繁体   中英

JS element onclick event not being fired

I have an <a> element, which I have selected using the dom. I have the following code:

var link = document.createElement("a");
var ce = function (e) {
   alert("A");
}
link.onclick = ce; // Or link.addEventListener("click", ce);
console.log(ce);
console.log(link.onlick);

In the console (chrome dev tools), I see the following:

function (e) { alert("A"); }

and then

undefined

Upon clicking the element, the event does not fire. I have noticed that applying the onclick to the same element from the console, however, does correctly apply the event.

How to I get this event to apply?

You need to add the link that you create to the DOM before you bind the onclick event.

Once you do this you will no longer get undefined for the log of the onclick event.

var link = document.createElement("a");
var ce = function (e) {
    alert("A");
}
// Add link to page 
document.body.appendChild(link);
link.onclick = ce; // Or link.addEventListener("click", ce);
console.log(ce);
console.log(link.onclick);

In fact, The problem is caused by a typo because you have:

console.log(link.onlick);// onlick !!

Instead of:

console.log(link.onclick);

Here's the full code:

var link = document.createElement("a");
      var ce = function (e) {
        alert("A");
      }
link.onclick = ce; // Or link.addEventListener("click", ce);
link.text="Click me!!";
document.body.appendChild(link);
console.log(link.onclick);// here you will get function (e) { alert("A"); }

And now it works fine, here's a DEMO .

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