簡體   English   中英

動態onclick,帶參數的匿名函數

[英]dynamic onclick, anonymous function with parameter

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

我只是想分配一個函數處理程序,該函數應該知道單擊了哪個圖像。

如果我沒記錯的話,這是分配圖像處理程序的兩步過程,並傳遞該圖像的引用。

什么是最安全的跨瀏覽器方式?

在函數內部使用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