javascript - jQuery onclick 没有获得正确的值

标签 javascript jquery html onclick

我试图在点击事件上获取图像 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);
    });
});

>> jsFiddle link

我错过了什么吗?

<小时/>

附注:我知道 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/

相关文章:

javascript - 如果长度为空,则需要通过一个条件

javascript - 如何用jquery选择特定的<li>获取value的attr值并显示在网站上

html - 媒体查询不生效。

html - 超链接的异常行为

javascript - 使用向下/向上滑动过渡动画 v-if (Vue.js 2)

javascript - 当前值未反射(reflect)在 reactjs 选择组件中

javascript - 如何在 jQuery 每个循环中处理第 n 个元素?

javascript - 旋转时如何使圆圈周围的文字不重叠

javascript - 为什么在 this.$scopedSlots 中也可以使用 Vue 常规插槽?

javascript - 为什么当我单击按钮时我会变得未定义?