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

时间:2012-06-03 22:34:47

标签: javascript jquery function onclick anonymous

所以我的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);
                }
            }
        };

我只是想分配一个函数处理程序,该函数应该知道单击了哪个图像。

如果我没记错的话,这是分配图像处理程序的两步过程,并传递该图像的引用。

最安全的跨浏览器方式是什么?

1 个答案:

答案 0 :(得分:2)

函数内的

使用this

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