想知道是否有人可以指出正确的方向,我正在尝试在页面上显示具有匹配类名称的“下一个”元素,即链接正下方的元素。
$(function() {
$("div.std-centered").hide();
$("a.show_hide").click(function(e) {
e.preventDefault();
$(this).closest('div.std-centered').next().show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-4 col sameHeight">
<p>Some blurb <a href="#" class="show_hide">i</a></p>
</div>
<div class="col-sm-2 col text-center sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
<div class="col-sm-2 text-center col sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
<div class="col-sm-2 text-center col sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
<div class="col-sm-2 text-center col sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
</div>
<div class="row">
<div class="col-sm-12 std-centered">
<p>This is the content</p>
</div>
</div>
带有类std-centered
的div被隐藏(在jQuery中),我试图在单击show_hide
链接时找到并显示它。
但我似乎无法控制该 div。有人能给我指出正确的方向吗?
谢谢, C
最佳答案
问题是因为 closest()
搜索 DOM 以查找父元素,但 .std-centered
div 是父元素的同级元素,因此不会被发现。
要解决此问题,您可以使用 closest()
查找 .row
,然后查找 next('.row')
和最后 find()
来获取你想要的元素,如下所示:
$(function() {
$("div.std-centered").hide();
$("a.show_hide").click(function(e) {
e.preventDefault();
$(this).closest('.row').next('.row').find('div.std-centered').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-sm-4 col sameHeight">
<p>Some blurb <a href="#" class="show_hide">i</a></p>
</div>
<div class="col-sm-2 col text-center sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
<div class="col-sm-2 text-center col sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
<div class="col-sm-2 text-center col sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
<div class="col-sm-2 text-center col sameHeight">
<p><span class="glyphicon glyphicon-ok"> </span></p>
</div>
</div>
<div class="row">
<div class="col-sm-12 std-centered">
<p>This is the content</p>
</div>
</div>
关于javascript - 显示 'Closest' div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45455735/