为什么 jQuery next 找不到下一个 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19624293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why jQuery next can't find the next div?
提问by Mohammad Saberi
I want to create a page for FAQs and used jQuery to show each answer. But it does not work.
The format of each question-answer is like this:
我想为常见问题创建一个页面并使用 jQuery 来显示每个答案。但它不起作用。
每个问答的格式是这样的:
<div><a href="javascript:void(0)" class="expand">First Question</a></div>
<div class="answer" style="display:none">First Answer</div>
And the jQuery code that I have used is:
我使用的 jQuery 代码是:
$(".expand").click(function(){
$(this).next('.answer').slideToggle();
});
Is it wrong? You can see its jsFiddletoo.
这是错的吗?你也可以看到它的jsFiddle。
回答by karthikr
The two elements are not at the same level for next()
to work.
这两个要素不是在同一水平next()
上起作用的。
Try this:
尝试这个:
$(".expand").click(function(){
$(this).parent().next('.answer').slideToggle();
});
Here is an updated fiddlefor your reference
这是一个更新的小提琴供您参考
回答by Cameron Askew
Because jQuery.next()
grabs siblings, the div you're trying to get is the parent's sibling, not the sibling.
因为jQuery.next()
抓取兄弟姐妹,所以你试图获得的 div 是父母的兄弟姐妹,而不是兄弟姐妹。
回答by Peter van der Wal
Well $(this) is the a-element, and there are no siblings to that element. If you want the div, use parent:
$(this) 是 a 元素,并且该元素没有兄弟元素。如果你想要 div,请使用 parent:
$(this).parent().next()