动态点击,带参数的匿名功能

dynamic onclick, anonymous function with parameter

本文关键字:功能 参数 动态      更新时间:2023-09-26

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

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

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

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

在函数中使用this

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