其实我想从最近的元素获取属性值。我无法从所需的元素中获取属性值。这就是我到目前为止所做的。 我进行了很多搜索,但几乎没有找到任何有用的东西。任何帮助将不胜感激。
<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>
关于javascript - 从所选元素 html 上方的元素获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28052080/