微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Jquery和html ::获取最近的数据属性

这是我现在正在处理的类似代码

<div class="gallery-category">
    <h2 data-gallery="Exterior">
        <span class="gallery-back"></span>
        Exterior
    </h2>
    <div class="gallery-items-wrap">
        <div class="gallery-image-tile">
            <div class="gallery-img" data-analytics="photo-click">
                <picture>
                    <source srcset="/content/image/image1.jpg">
                </picture>
            </div>
        </div>
    </div>
</div>

<div class="gallery-category">
    <h2 data-gallery="Interior">
        <span class="gallery-back"></span>
        Interior
    </h2>
    <div class="gallery-items-wrap">
        <div class="gallery-image-tile">
            <div class="gallery-img" data-analytics="photo-click">
                <picture>
                    <source srcset="/content/image/image2.jpg">
                </picture>
            </div>
        </div>
    </div>
</div>

如果我点击图片image1.jpg,我必须得到值外观.我创建了数据属性数据库,并试图通过使用$(‘[data-gallery]’).data(“gallery”)来获取值,但只获取一个值.

我需要的东西看起来像这样:

单击image1获取值“外部”.

单击image2获取值’Interior’.

提前致谢

解决方法:

是的,您可以通过将单击附加到类.gallery-img然后在单击后使用nearest()方法转到parent div并找到具有data-gallery属性的h2元素:

$('.gallery-img picture').on('click',function(){
    $(this).closest('.gallery-category').find('h2[data-gallery]').data("gallery")
})

希望这可以帮助.

$('.gallery-img picture').on('click',function(){
  var gallery_data = $(this).closest('.gallery-category').find('h2[data-gallery]').data("gallery");
  
  console.log(gallery_data);
})
picture {
  width: 100px;
  height: 20px;
  border: 1px solid;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery-category">
  <h2 data-gallery="Exterior">
    <span class="gallery-back"></span>
    Exterior
  </h2>
  <div class="gallery-items-wrap">
    <div class="gallery-image-tile">
      <div class="gallery-img" data-analytics="photo-click">
        <picture>
          <source srcset="/content/image/image1.jpg">
        </picture>
      </div>
    </div>
  </div>
</div>

<div class="gallery-category">
  <h2 data-gallery="Interior">
    <span class="gallery-back"></span>
    Interior
  </h2>
  <div class="gallery-items-wrap">
    <div class="gallery-image-tile">
      <div class="gallery-img" data-analytics="photo-click">
        <picture>
          <source srcset="/content/image/image2.jpg">
        </picture>
      </div>
    </div>
  </div>
</div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐