【问题标题】:jQuery: Rearranging Elements Without RepeatingjQuery:重新排列元素而不重复
【发布时间】:2014-04-25 05:25:24
【问题描述】:

假设你有这样的 HTML:

<div class="section">
    <div class="bottom">bottom</div>
    <div class="top">top</div>
</div>
<div class="section">
    <div class="bottom">bottom</div>
    <div class="top">top</div>
</div>

并且您想使用 jQuery 在每个 .section 中将 .top 移动到 .bottom 上方。

我正在尝试这样做:

$('.section').each(function (i, obj) {
    $('.bottom').insertAfter('.top');
});

但这会导致“底部”在每个部分重复四次。

小提琴:http://jsfiddle.net/TLejL/

我做错了什么?

【问题讨论】:

    标签: jquery each dom-manipulation insertafter


    【解决方案1】:

    尝试在.each() 函数中使用$(this) 引用,

    $('.section').each(function (i, obj) {
        $(this).find('.bottom').insertAfter($(this).find('.top'));
    });
    

    $('.top').each(function() {
        $(this).closest('.section').prepend($(this));
    });
    

    DEMO

    【讨论】:

    • 做到了!这是实现这一目标的最有效方法吗?
    • @ErikBerger 第一个只是对您的代码的模仿,但第二个会更快。
    【解决方案2】:

    您需要定位当前section中的顶部和底部元素

    $('.section .top').after(function (i, obj) {
        return $(this).prev()
    });
    

    演示:Fiddle

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 2019-04-23
      相关资源
      最近更新 更多