简体   繁体   English

动态onclick,带参数的匿名函数

[英]dynamic onclick, anonymous function with parameter

so my javascript is a bit rusty.. i am trying to do this: 所以我的javascript有点生锈..我正在尝试这样做:

        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 : 在函数内部使用this

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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