我想在所有具有相同类别的锚点之后选择第一个下一个元素。HTML
<a class="some_anchors">
</a>
<ul id="ul_1">
</ul>
...
<a class="some_anchors">
</a>
<ul id="ul_2">
</ul>
...
<a class="some_anchors">
</a>
<ul id="ul_3">
</ul>
...
<a class="some_anchors">
</a>
<ul id="ul_4">
</ul>
...
现在我要选择全部ul1,ul2,ul3,ul4
。我在这里尝试过:
console.log($(".some_anchors").nextAll('ul:first'));
但是它仅返回ul1
。如何解决这个问题?
您可以使用下一个同级选择器+
直接在类元素之后定位ul。
console.log(
$('.some_anchors + ul').get()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="some_anchors">
</a>
<ul id="ul_1">
</ul>
<ul class="not-me">
</ul>
<a class="some_anchors">
</a>
<ul id="ul_2">
</ul>
<ul class="not-me">
</ul>
<a class="some_anchors">
</a>
<ul id="ul_3">
</ul>
<ul class="not-me">
</ul>
<a class="some_anchors">
</a>
<ul id="ul_4">
</ul>
<ul class="not-me">
</ul>
使用以下内容:
$(function() {
var lists = [];
$(".some_anchors").each(function(i, el) {
lists.push($(el).next());
});
console.log(lists);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="some_anchors">
</a>
<ul id="ul_1">
</ul>
<a class="some_anchors">
</a>
<ul id="ul_2">
</ul>
<a class="some_anchors">
</a>
<ul id="ul_3">
</ul>
<a class="some_anchors">
</a>
<ul id="ul_4">
</ul>
我认为这可能对您有帮助
$('li').each(function () {
if ($(this).hasClass("some_anchors")) {
$(this).show();
} else {
$(this).hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="width:500px;" class="siblings">
<ul>
<li>li (No Class)</li>
<li>li (No Class)</li>
<li>li (No Class)</li>
<li class="some_anchors">li (sibling with class name "some_anchors")</li>
<li>li (No Class)</li>
<li>li (No Class)</li>
</ul>
</div>