Javascript 如何使用jQuery获取图像ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3890886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:31:16  来源:igfitidea点击:

How to get image id using jQuery?

javascriptjqueryimageattributesonload

提问by gautamlakum

I have written code like this. <img id='test_img' src='../../..' />

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

I want to get the id of this image on image load like,

我想在图像加载时获取此图像的 ID,例如,

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

Can you please help me?

你能帮我么?

Thanks.

谢谢。

回答by Mouhannad

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

good luck!!

祝你好运!!

edit:

编辑:

   //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")

回答by Andy E

Don't use $(this).attr('id'), it's taking the long, inefficient route. Just this.idis necessary and it avoids re-wrapping the element with jQuery and the execution of the attr()function (which maps to the property anyway!).

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

$(img).load(function() {
   alert(this.id);
});

回答by gautamlakum

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

回答by Gazler

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