javascript jquery 获取 img src onclick 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25890566/
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
jquery get img src onclick event
提问by guy
I am having trouble referring to an image on an onclick evet.
我在引用 onclick evet 上的图像时遇到问题。
my example is that the "this" reference points to an element that has couple of images and i want to change a specific image.
我的例子是“this”引用指向一个有几个图像的元素,我想改变一个特定的图像。
<li class = "header_det">
<table width="100%" style="font-size:14px;">
<tr>
<td width="10%" align = "right" rowspan = "2">text</td>
<td width="80%"><img width="30" height="30" src="images/map_white_pin.png" ></a></td>
<td width="10%" align = "center" class = "header_pic"><img width="20" height="20" src="images/route_det/down_arrow.png" ></td>
</tr>
</table>
</li>
The js code for the onclick event is this:
onclick事件的js代码是这样的:
$(".header_det_map").click(function() {
var img_type = $(this).attr(".header_pic img").attr("src") ;
if(img_type == "images/route_det/down_arrow.png") {
$(this).attr(".header_pic img").attr('src', "images/route_det/up_arrow.png");
} else{
$(this).attr(".header_pic img").attr('src', "images/route_det/down_arrow.png");
}
});
this code doesn't work, and i have to use the this pointer because i have other
此代码不起作用,我必须使用 this 指针,因为我还有其他
Thanx
谢谢
回答by Jonas Grumann
I think this line:
我认为这一行:
var img_type = $(this).attr(".header_pic img").attr("src") ;
should be:
应该:
var img_type = $(this).find(".header_pic img").attr("src") ;
回答by pistou
All you jquery is wrong : .header_pic img
is not an attribute but an element of .header_det_map
你所有的 jquery 都是错的:.header_pic img
不是一个属性而是一个元素.header_det_map
Plus, you're HTML is a bit messy :
另外,你的 HTML 有点乱:
- You shouldn't have space between attribute name and value in your HTML
- There is closing
</a>
tags - You should close
'<img />
tags
- HTML 中的属性名称和值之间不应有空格
- 有结束
</a>
标签 - 你应该关闭
'<img />
标签
<li class="header_det">
<table width="100%" style="font-size:14px;">
<tr>
<td width="10%" align="right" rowspan="2">text</td>
<td width="80%">
<img width="30" height="30" src="images/map_white_pin.png" />
</td>
<td width="10%" align="center" class="header_pic">
<img width="20" height="20" src="images/route_det/down_arrow.png" />
</td>
</tr>
</table>
</li>
$(".header_det_map").click(function() {
var img = $(this).find(".header_pic img"); // use a variable to store your image element in case you have to change the container class
var img_type = img.attr("src"); // not necessary to store it, could be use as it in the if statement
if(img.attr("src") == "images/route_det/down_arrow.png") {
img.attr("src", "images/route_det/up_arrow.png");
} else {
img.attr("src", "images/route_det/down_arrow.png");
}
});