Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jQuery获取图像id?_Javascript_Jquery_Image_Attributes_Onload - Fatal编程技术网

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

Javascript 如何使用jQuery获取图像id?,javascript,jquery,image,attributes,onload,Javascript,Jquery,Image,Attributes,Onload,我写过这样的代码 我想在图像加载时获取该图像的id $(img).load(function() { // Here I want to get image id i.e. test_img }); 你能帮帮我吗 谢谢 $(img).load(function() { var id = $(this).attr("id"); //etc }); 祝你好运 编辑: //suggested by the others (most efficient) var id = t

我写过这样的代码<代码>

我想在图像加载时获取该图像的id

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

谢谢

$(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")
不要使用
$(this).attr('id')
,这是一条漫长而低效的路线。只需
这个.id
是必需的,它可以避免使用jQuery重新包装元素和执行attr()函数(无论如何,它都会映射到属性!)


这是加载函数中的.id。请考虑@Andy E的建议。创建一个jQuery对象并调用一个方法来提取一个属性值是没有意义的,这个属性值可以通过直接引用属性名来获取。我想你们都是对的。我尝试了所有的答案,都成功了。谢谢大家。
$(img).load(function() {
   alert($(this).attr('id'));
});
$(img).load(function() {
   alert(this.id);
});
$(function() {
    $('img#test_img').bind('load', function() {
        console.log(this.id);  //console.log($(this).attr('id'));
    });
});