它有效:
<div class="xpav">
Create
</div>
<div class="apr" style="display: none;">
sometext
</div>
<script>
$('.xpav').click(function() {
$(this).next(".apr").slideDown("fast");
})
</script>
事实并非如此:
<div class="xpav">
Create
</div>
<br />
<div class="apr" style="display: none;">
sometext
</div>
<script>
$('.xpav').click(function() {
$(this).next(".apr").slideDown("fast");
})
</script>
为什么
会破坏它?
最佳答案
.next()
只查看给定元素之后的元素,然后根据选择器检查该元素(如果提供)。在第二个示例中,由于 br
存在并且没有 apr
类,因此不会拾取它。来自 API 文档:
Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
您的第二个示例需要使用 .nextAll()
而是搜索所有下一个兄弟:
$('.xpav').click(function() {
$(this).nextAll(".apr").slideDown("fast");
});
要仅选取第一个匹配的 .apr
,请使用 .eq(0)
:
$('.xpav').click(function() {
$(this).nextAll(".apr").eq(0).slideDown("fast");
});
关于javascript - 接下来谁能解释一下 jQuery 中这种奇怪的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5706979/