简体   繁体   中英

dynamic onclick, anonymous function with parameter

so my javascript is a bit rusty.. i am trying to do this:

        var images = document.getElementsByTagName("img");
        for (var i = images.length - 1; i >= 0; i--) {
            var image = images[i];
            if (image.className == "photo latest_img") {
                image.onclick = function() {
                    // here i will perform a different action depending on what image was clicked           
                    alert(image.src);
                }
            }
        };

i am just trying to assign a function handler, and that function should be aware of which image was clicked.

if i remember correctly, this was a 2 step process to assign a image handler, and pass a reference of that image.

what's the safest cross browser way to do this?

inside the function use this :

image.onclick = function() {
    // here i will perform a different action depending on what image was clicked           
    alert(this.src);
}

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