我想在一个页面上有多个元素,这些元素将在单击标题跨度时切换下一个内容跨度的可见性。所有内容跨度内容都隐藏在文档准备好时。
内容切换在针对整个类时有效,但在尝试从被单击的标题范围中定位下一个内容范围元素时无效。
当我们试图操纵通过 telerik radeditor 输入的文本时,正在使用特定标记
HTML
<p>
<span class="collapsibleHeader">Content Header</span><br />
<span class="collapsibleContent">Sed dignissim velit non congue consequat.</span>
</p>
<p>
<span class="collapsibleHeader">Content Header</span><br />
<span class="collapsibleContent">Sed dignissim velit non congue consequat.</span>
</p>
JQuery
$(document).ready(function () {
$('.collapsibleContent').hide();
$('.collapsibleHeader').click(function (e) {
$(this).parent().next('.collapsibleContent').toggle();
e.preventDefault();
});
});
最佳答案
您将上升一级,到达 p
元素,然后 next
到下一个元素(见下一个注释),但是 .collapsibleContent
是那个p
的 child 和一个 <br/>
实际上是 next()
元素到 p
(所以过滤器也不匹配任何东西)。 next()
只返回下一个元素,然后应用过滤器以查看它是否匹配。
删除 parent()
并使用 nextAll()
使用您的选择器:
$(document).ready(function () {
$('.collapsibleContent').hide();
$('.collapsibleHeader').click(function (e) {
$(this).nextAll('.collapsibleContent').toggle();
e.preventDefault();
});
$('.collapsibleContent2').hide();
$('.collapsibleHeader2').click(function (e) {
$('.collapsibleContent2').toggle();
e.preventDefault();
});
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/hn5ss2au/3/
您可以使用 siblings()
使用相同的过滤器,但比 nextAll()
慢.如果碰巧每场比赛不止一场,还要加上first()
例如
$(this).nextAll('.collapsibleContent').first().toggle();
备注:nextall
比 siblings()
的替代品更快和 parent().children()
: http://jsperf.com/jquery-next-vs-siblings/5
关于javascript - 找不到下一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28436901/