从所选元素 html 上方的元素获取属性值

Getting an attribute value from the element above the selected element html

本文关键字:元素 获取 属性 html      更新时间:2023-09-26

>实际上我想从最近的元素中获取属性值。我无法从所需的元素中获取属性值。这就是我到目前为止所做的。我搜索了很多,几乎没有想出任何有用的东西。任何帮助将不胜感激。

<div class="col-sm-4">
    <div class="grid mask">
        <figure>
            <div>
                 <h4>Hello There</h4> 
                 <span data-id="1"></span>
            </div>
            <img class="img-responsive" src="../dist/img/team/subhan.png" alt="">
            <figcaption> 
                <a data-toggle="modal" href="#myModal" onclick="alert($(this).closest('span').attr('data-id').html())">Find</a>
            </figcaption>
        </figure>
    </div>
</div>

使用更具体的 DOM 遍历函数。另外,您不应该使用.html(); .attr() 以字符串的形式返回属性的值,而不是需要提取其内容的元素。

$("a").click(function() {
    alert($(this).closest('figure').find('span[data-id]').data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4">
  <div class="grid mask">
    <figure>
      <div>
        <h4>Hello There</h4> 
        <span data-id="1"></span>
      </div>
      <img class="img-responsive" src="../dist/img/team/subhan.png" alt="">
      <figcaption>
        <a data-toggle="modal" href="#myModal">Find</a>
      </figcaption>
    </figure>
  </div>
</div>