2014-09-03 67 views
0

getAttribute如何适用于多个图像? 任何一个heip可以吗?getAttribute for multiple images

<script> 
    $(document).ready(function(){ 
    $(".img").click(function(){ 
     var img = $(this).getAttribute('src'); 
     alert(img.getAttribute('src')); // foo.jpg 
     alert(img.src);     // http://..../foo.jpg 
    }); 
    }); 
</script> 

</head> 
    <body> 
    <img class="img" src="foo.jpg" > 
    <img class="img" src="foo1.jpg" > 
    <img class="img" src="foo2.jpg" > 
    </body> 
</html> 
+2

你在做什么? – 2014-09-03 12:38:19

+0

使用jQuery的'.attr()'来获取元素的属性,或者在使用本地方法之前突破jQuery。 – ndugger 2014-09-03 12:57:45

回答

-1

你需要将jquery对象转换为普通的javascript对象来使用它的本地方法和属性。您已在this上下文中拥有该对象。因此,使用:

$(".img").click(function(){ 
    this.getAttribute('src'); // when using with jquery $(this)[0].getAttribute('src') 
}); 
+2

'$(this)[0] .getAttribute('src')'是啊,啊,与智能相反。如果你真的想要一个'$',可以使用'this.src'或$(this).attr('src')'。 – 2014-09-03 12:39:19

+0

@dystroy:我只在编辑。从js对象中创建jquery对象,然后再次回复是毫无价值的:) – 2014-09-03 12:40:21

+0

'$(this).attr(“src”)'是你应该使用的。在原生DOM和jQuery之间进行翻转可能性并不坏,但你最终会混淆新手。 – ndugger 2014-09-03 12:50:01

0

我认为这是你想要的! 只是把他们都弄到:

$(".img").each(function(){ 
    alert(this.getAttribute("src")); 
}); 

或者在你的代码示例:

$(".img").click(function(){ 
    var img = this.getAttribute('src'); 
}); 

最后,你可以使用.attr();

$(".img").each(function(){ 
     alert($(this).attr("src")); 
    });