2010-10-08 99 views
4

我寫過這樣的代碼。 <img id='test_img' src='../../..' />如何使用jQuery獲取圖像ID?

我想對像圖像加載這一形象的ID,

$(img).load(function() { 
// Here I want to get image id i.e. test_img 
}); 

你能幫幫我嗎?

謝謝。

+1

this.id您的負載函數中。 – 2010-10-08 13:22:51

+1

考慮@Andy E的建議。創建一個jQuery對象並調用一個方法通過直接引用屬性名稱來提取可用的屬性值是沒有意義的。 – user113716 2010-10-08 13:43:21

回答

8
$(img).load(function() { 
    var id = $(this).attr("id"); 
    //etc 
}); 

祝你好運!

編輯:

//suggested by the others (most efficient) 
    var id = this.id; 

    //or if you want to keep using the object 
    var $img = $(this); 
    var id = $img.attr("id") 
+0

感謝所有。我想你們都是對的。我嘗試了所有的答案,所有的工作。感謝大家。 – gautamlakum 2010-10-08 13:31:53

1
$(img).load(function() { 
    alert($(this).attr('id')); 
}); 
8

不要使用$(this).attr('id'),它採取的長,效率低的路線。只需要this.id是必要的,它避免了使用jQuery重新包裝元素並執行attr()函數(它無論如何映射到屬性!)。

$(img).load(function() { 
    alert(this.id); 
}); 
3
$(function() { 
    $('img#test_img').bind('load', function() { 
     console.log(this.id); //console.log($(this).attr('id')); 
    }); 
});