gpt4 book ai didi

javascript - 接下来谁能解释一下 jQuery 中这种奇怪的行为吗?

转载 作者:行者123 更新时间:2023-11-28 11:27:44 25 4
gpt4 key购买 nike

它有效:

<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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com