jQuery insert最后一项之后 [英] jQuery insertAfter last item
本文介绍了jQuery insert最后一项之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
<div class="main">
<a class="blah">blah1</a>
</div>
<div class="main">
<a class="blah">blah2</a>
</div>
<div class="main reply">
<a class="blah">blah3</a>
</div>
<div class="main reply">
<a class="blah">blah4</a>
</div>
<div class="main reply">
<a class="blah">blah5</a>
</div>
<div class="main">
<a class="blah">blah6</a>
</div>
<div class="main reply">
<a class="blah">blah7</a>
</div>
在单击a.blah
时,我需要在父级 .main
之后的最新.reply
后面附加<div class="new">xxx</div>
之类的内容,这意味着它应该找到最新的.reply
agter a.blah
的父级,并且不应与另一个.main
交叉,这是我编码的内容(但不起作用):
on click of a.blah
, I need to append something like <div class="new">xxx</div>
to the latest .reply
after the parent .main
, it means it should find the latest .reply
agter the parent of the a.blah
, and it should not cross to another .main
, here is what I coded (but not working):
$('.blah').on('click', function(){
var new_add = '<div class="new">xxx</div>';
$(this).parents('div.main').next('.main:last').append(new_add);
});
我该如何解决? 谢谢
推荐答案
基于评论
$('.blah').on('click', function(){
var new_add = '<div class="new">xxx</div>';
$(this).closest('.main').nextUntil('.main:not(.reply)').addBack().last().after(new_add);
});
演示:小提琴
- .closest()查找与选择器匹配的直接祖先
- .nextUntil()查找当前
.main
之后的所有.reply
元素,而没有在没有.reply
的情况下越过 - .addBack()重新添加当前父对象,以防下一个
.main
不是.reply
- .last()从匹配集中找到最后一个元素
- .after()在匹配的元素集之后插入传递的元素
.main
- .closest() find the immediate ancestor matching the selector
- .nextUntil() finds all the
.reply
elements coming after the current.main
without crossing over a.main
without.reply
- .addBack() adds back the current parent, incase the next
.main
is not.reply
- .last() finds the last element from the matched set
- .after() inserts the passed element after the matched set of element
这篇关于jQuery insert最后一项之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文