聘我网

新概念招聘3.0

如何用jQuery实现这个需求?

vote up0vote downstar
<strong>title</strong>

<cite>...</cite>
<cite>...</cite>
...
<a>ank</a>

要在<strong>后面的第一个<cite>后面插入一个元素$el

但是如果<strong>后面没有<cite>,则直接插到<strong>之后

 

1 个答复

vote up0vote downcheck
$el.insertAfter($("strong, strong ~ cite:last").eq(-1))

其中~的定义为:

~ Selects all sibling elements that follow after the "prev" element, have the same parent, and match the filtering "siblings" selector. source

更新

注意eq(-1)jQuery1.4才有的特性,在老版本可以这样(伪代码):

var sLen = $(selector).length;
$(selector).eq(sLen-1);

更新

最鲁棒的方案是:

var anchor = $('strong');
while (anchor.next('cite').length) {
  anchor = anchor.next();
}
anchor.after($el);
链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.