Javascript 如何使用jQuery获取图像id?
我写过这样的代码<代码> 我想在图像加载时获取该图像的idJavascript 如何使用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
$(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'));
});
});