简体   繁体   中英

Javascript onclick event not attaching

I'm attempting to attach and onclick event to an img tag that I created in Javascript, but for some reason it does not want to attach. In my current code, I have:

var img = document.createElement('img');
img.src = pictures[picIndex][0];
img.alt = 'pic';
img.id = "picture_" + picIndex;
img.onclick = function() { alert('click') };
document.getElementById('container').appendChild(img);

But when I load my site, I get everything but the onclick event, and clicking the image does nothing:

<img src=".." alt="pic" id="picture_3">

Why isn't it being appended? I've also tried

img.onclick = myFunction;

function myFunction() {
    alert('click');
}

and the same thing happens. If I manually edit the img tag to include the onclick function, the function executes just fine, but I can't for the life of me figure out why it isn't attaching when I create the element.

If you copy and pasted your code in, it looks to be a typo

img.onlclick =

should be

img.onclick =

Here is a demo Fiddle: http://jsfiddle.net/mifi79/CE7PP/

Your problem may be in the ordering- if your JS is on the page prior to the <div id="container"></div> (for example in the <head> ), the document.getElementById will not be able to operate on it as it does not yet exist.

The onclick event won't show up inline in the HTML because the image was instantiated as a Javascript object and the onclick handler exists as a property on the image object. I created an updated Fiddle ( http://jsfiddle.net/mifi79/CE7PP/1/ ) that outputs the value of the image objects onclick property to the console.

It is possible that your event is not working because you're not using the addEventListener method for non-IE browsers. Perhaps try this.

img.addEventListener('click', function () { /* your function here */ }, false);

/* MS fallback */

(img.attachEvent) ? img.attachEvent('onclick', function () { /* func here */ }) : img.addEventListener('click', function () { /* func here */ }, 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