简体   繁体   English

如何使用jQuery获取HTML中的下一个连续相似标签

[英]How to get next consecutive similar tag in html using jquery

I have something like following code in HTML which is generated from some of plugins. 我有一些类似的代码,这些代码是由一些插件生成的HTML。

<div class="parent">
  <span>item1</span>
  <input type="hidden"></input>
  <span>item2</span>
  <span class="active">item3</span>
  <input type="hidden"></input>
  <input type="hidden"></input>
  <span>item5</span>
  <input type="hidden"></input>
  <span>item6</span>
  <input type="hidden"></input>
</div>

I have at top "move up" and "move down" button and by click on it will move span either up or down. 我在顶部有“向上移动”和“向下移动”按钮,通过单击它可以向上或向下移动跨度。

Now what i want, from any of the selected/active span I need next span tag. 现在我想要的是,从任何选定的/活动范围中,我都需要下一个范围标签。 when i am using $(this).next() then it give me hidden input, when I use $(this).next("span") then it not give me next span. 当我使用$(this).next()它给我隐藏的输入,当我使用$(this).next("span")它不给我下一个跨度。

so what should be jquery snippet to get from selected span i can get either next or previous similar tag (eg. span in my case)? 那么从所选范围中获取的jquery片段应该是什么,我可以得到下一个或上一个类似的标签(例如,在我的情况下为span)?

Update: This is the Jquery code I am using 更新:这是我正在使用的Jquery代码

$('.btn-move-up').click(function () {
       var $current = $('.parent > span.active');       
       var $prev = $current.prev();    
            $prev.before($current);
        });
$('.btn-move-down').click(function () {
     var $current = $('.parent > span.active');                       
     var $next = $current.next();
     $next.after($current);         
});

Thanks 谢谢

next() and prev() alone won't work given your HTML structure as the span elements are not always direct siblings. 给定您的HTML结构,仅next()prev()不能工作,因为span元素并不总是直接的同级。

To fix this you can use nextAll('span').first() and prevAll('span').first() : 要解决此问题,您可以使用nextAll('span').first()prevAll('span').first()

 $('.btn-move-up').click(function() { var $current = $('.parent > span.active'); var $prev = $current.prevAll('span').first(); $prev.before($current); }); $('.btn-move-down').click(function() { var $current = $('.parent > span.active'); var $next = $current.nextAll('span').first(); $next.after($current); }); 
 .active { color: #C00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> <span>item1</span> <input type="hidden" /> <span>item2</span> <span class="active">item3</span> <input type="hidden" /> <input type="hidden" /> <span>item5</span> <input type="hidden" /> <span>item6</span> <input type="hidden" /> </div> <button class="btn-move-up">Up</button> <button class="btn-move-down">Down</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM