我试图在点击事件上获取图像 ALT 值,但它没有按预期工作,并且在点击时显示相同的值(图像 ALT)。
这是代码:
HTML:
<a href="//cdn.shopify.com/s/files/1/0720/9527/products/MDM02-south-east-postcode-district-map-detail-large_ee8e2826-b33b-4c77-83b2-f162df33ec33_large.gif?v=1420644155" class="product-photo-thumb" title="Map 1">
<img id="imgVariants" src="//cdn.shopify.com/s/files/1/0720/9527/products/MDM02-south-east-postcode-district-map-detail-large_ee8e2826-b33b-4c77-83b2-f162df33ec33_compact.gif?v=1420644155" alt="Map 1">
</a>
<a href="//cdn.shopify.com/s/files/1/0720/9527/products/png_large.png?v=1420644163" class="product-photo-thumb" title="Map 2">
<img id="imgVariants" src="//cdn.shopify.com/s/files/1/0720/9527/products/png_compact.png?v=1420644163" alt="Map 2">
</a>
Javascript/jQuery
$(document).ready(function(){
$('.product-photo-thumb').on("click", function (e) {
e.preventDefault();
alert(document.getElementById("imgVariants").alt);
});
});
我错过了什么吗?
<小时/>附注:我知道 ID 必须是唯一的,但我想要一个即使没有唯一 ID 也能工作的解决方案。
最佳答案
有两个元素具有相同的 Id
(不应该),删除它们,您应该使用类似 e.target
这是一个工作示例.. http://jsfiddle.net/83cyuozz/1/
$(document).ready(function(){
$('.product-photo-thumb').on("click", function (e) {
e.preventDefault();
alert(e.target.alt);
});
});
关于javascript - jQuery onclick 没有获得正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27837100/