jQuery insert最后一项之后 [英] jQuery insertAfter last item

查看:85
本文介绍了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);
});

演示:小提琴

  1. .closest()查找与选择器匹配的直接祖先
  2. .nextUntil()查找当前.main之后的所有.reply元素,而没有在没有.reply
  3. 的情况下越过.main
  4. .addBack()重新添加当前父对象,以防下一个.main不是.reply
  5. .last()从匹配集中找到最后一个元素
  6. .after()在匹配的元素集之后插入传递的元素
  1. .closest() find the immediate ancestor matching the selector
  2. .nextUntil() finds all the .reply elements coming after the current .main without crossing over a .main without .reply
  3. .addBack() adds back the current parent, incase the next .main is not .reply
  4. .last() finds the last element from the matched set
  5. .after() inserts the passed element after the matched set of element

这篇关于jQuery insert最后一项之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆