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>

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...