如何在jquery中使用图像ID获取图像位置
How to get the image location using image id in jquery
我在一个页面中有几张图片。
<a href="http://imagelocation" id="image-selected[0]"><img src="http://imagelocation" alt=""></a>
<a href="http://imagelocation" id="image-selected[1]"><img src="http://imagelocation" alt=""></a>
<a href="http://imagelocation" id="image-selected[2]"><img src="http://imagelocation" alt=""></a>
现在,如果我单击任何图像,我需要在jquery变量中获取图像位置。我怎样才能得到它?
我试过这个,但没有工作。
$('#image-selected').click(function(){
alert($('#image-selected').attr('href'));
})
你最好改用一个普通类...但是关于您的问题,您可以使用 startsWith 属性选择器:
$('[id^=image-selected]').click(function(){
alert($(this).attr('href'));
})
试试这个:
.html:
<a href="http://imagelocation" class="image-selected"><img src="http://imagelocation" alt=""></a>
<a href="http://imagelocation" class="image-selected"><img src="http://imagelocation" alt=""></a>
<a href="http://imagelocation" class="image-selected"><img src="http://imagelocation" alt=""></a>
jquery:
$('.image-selected').click(function(){
alert($(this).attr('href'));
})
简单!您希望启动事件的元素:)
$('img').click(function(){
alert($(this).attr('src'));
}
最好使用类而不是 id,因为 id 用作唯一标识符
如果需要,只需更新链接的图像位置:
$('[id^=image-selected]').click(function(){
alert('img',$this).attr('src');
});
我建议使用类在所有链接上触发jquery函数,如下所示:
<a href="http://imagelocation" class="imgLink" id="image-selected[0]"><img src="http://imagelocation" alt=""></a>
<a href="http://imagelocation" class="imgLink" id="image-selected[1]"><img src="http://imagelocation" alt=""></a>
<a href="http://imagelocation" class="imgLink" id="image-selected[2]"><img src="http://imagelocation" alt=""></a>
现在,您的jquery可以像以下一样简单:
$('.imgLink').click(function(){
alert('img',$this).attr('src');
});
相关文章:
- 获取图像ID并更改图像JavaScript
- 画布中的图像id
- 如何在jquery中使用图像ID获取图像位置
- 如何在点击该图像时在 canavs html5 中获取图像 ID
- 如何将图像 ID 传递给 JavaScript 页面
- 如何获取图像id
- 附加图像Id
- 通过jquery将图像id传递给php-mysql查询
- html图像id和画布
- 图像id未显示
- 当用户单击图像时传递图像名称或图像id属性
- 滑块图像id
- 单击时获取图像 ID 并将其设置为变量
- Konva从点击事件中获取图像ID
- 在dropzone .js的预览模板中为每个图像添加图像id
- 使用图像id保存图像为png, jpg和pdf
- 我需要从脚本中删除rel属性平均值,而不是图像id或任何值
- 将图像ID传递给函数
- 从touchstart事件javascript获取图像ID
- 无法引用图像id javascript