有没有办法轻松做nextUntil,让选择器匹配的元素被包含在内?我有这个,只有在有前一个兄弟姐妹的情况下才可以:
$("#content").find("h3:first").prev().nextUntil("ul:last").wrapAll("<div id='collapse'></div>");
有没有办法轻松做nextUntil,让选择器匹配的元素被包含在内?我有这个,只有在有前一个兄弟姐妹的情况下才可以:
$("#content").find("h3:first").prev().nextUntil("ul:last").wrapAll("<div id='collapse'></div>");
在选择器的末尾删除.prev()
、替换.nextUntil
为.nextAll
和使用.addBack()
,如下所示:
$("#content").find("h3:first").nextAll("ul:last").addBack().wrapAll("<div id='collapse'></div>");
Pre 1.8 应该使用andSelf
而不是addBack
我发现的解决方法是获取length
using nextUntil
(or prevUntil
),然后使用slice()
这个长度 + 1 on nextAll()
:
var inclusiveNextUntil = $(this).nextUntil( '.some-class' ).length;
var inclusiveNextUntil = $(this).nextAll().slice( 0 , inclusiveNextUntil + 1 );
这很笨拙,但很有效。高温高压
Fwiw在 nextAll docs Biziclop 中提到添加+ *
:
$obj.nextUntil('.last-item-to-include + *')
但这对我不起作用:/
这就是我所做的。我认为它比其他建议更清洁。
var elearr = $('selector1').nextUntil('selector2');
var lastele = elearr[elearr.length-1];
elearr.push($(lastele).next());
var s = $("li.start").nextUntil("li.stop");
s = s.add(s.last().next()).add(s.first().prev());
//and do whatever you need to with s
我认为是最直观的。全部使用 jQuery 方法制作。无需搜索两次。易于理解且易于记忆。
我认为正确的答案是
$("#content").find("h3:first").nextUntil("ul:last").addSelf().wrapAll("<div id='collapse'></div>");
正如其他人所回答的那样,使用.addSelf()
是使起始元素具有包容性的解决方案。
$("#content").find("h3:first").nextUntil("ul:last").addSelf().wrapAll("<div id='collapse'></div>");
并且为了使结尾元素具有包容性,使用该.nextUntil(".class + *")
方法解决了这个问题。
$("#content").find("h3:first").nextUntil("ul:last + *").addSelf().wrapAll("<div id='collapse'></div>");