如何使用jQuery获取图像ID?

gau*_*kum 4 javascript jquery attributes image onload

我写了这样的代码. <img id='test_img' src='../../..' />

我想在图像加载上获得此图像的ID,如,

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

你能帮我么?

谢谢.

Mou*_*nad 8

$(img).load(function() {
   var id = $(this).attr("id");
   //etc
});
Run Code Online (Sandbox Code Playgroud)

祝好运!!

编辑:

   //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")
Run Code Online (Sandbox Code Playgroud)


And*_*y E 8

不要使用$(this).attr('id'),它采取了漫长而低效的路线.只是this.id必要的,它避免了使用jQuery重新包装元素和执行attr()函数(无论如何映射到属性!).

$(img).load(function() {
   alert(this.id);
});
Run Code Online (Sandbox Code Playgroud)