【问题标题】:Detach, sort and reattach at the original position在原始位置分离、排序和重新附加
【发布时间】:2019-04-02 11:43:23
【问题描述】:

我有以下 HTML:

<div id="01" class="visible" data-owner="b"></div>
<div id="02" class="notvisible" data-owner="c"></div>
<div id="03" class="visible" data-owner="x"></div>
<div id="06" class="notvisible" data-owner="a"></div>
<div id="08" class="notvisible" data-owner="b"></div>

我想将可见的不同行分组并过滤到所有者组中:

<div class="group" data-user-group="x">
  <div id="03" class="visible" data-owner="x"></div>
</div>
<div class="group" data-user-group="b">
  <div id="01" class="visible" data-owner="b"></div>
</div>

用于此的 jQuery 代码效果很好:

function groupTheVisible() {
  $('div.group').each(function() {
    dataAnchor = $(this).attr('data-user-group');
    $('div.visible[data-owner="' + dataAnchor + '"]').detach().prependTo($(this));
  }  
}

function regroupTheVisible() {
  // ?
}

如何将可见行分组回到原始列表中的正确位置?提前致谢!

【问题讨论】:

  • 原始元素是否按其数字id 排序?此外,您的 JS 暗示在您进行排序之前存在 .group 元素。如果是这样,您能否提供一个包含所有相关代码的完整 HTML 示例。

标签: jquery sorting append clone detach


【解决方案1】:

如果您的第一个列表位于容器中会更容易,因为在极端情况下,该列表可能为空,然后脚本需要知道在哪里再次创建它。

所以,我将假设一个容器 divid “篮子”。

下面的 sn-p 在 div 元素中也有一些文本,以便输出显示正在发生的事情。

function groupTheVisible() {
    $("div.group").each(function() {
        var dataAnchor = $(this).attr("data-user-group");
        $('div.visible[data-owner="' + dataAnchor + '"]').prependTo(this);
    });
}

function regroupTheVisible() {
    $("div.group > div").each(function() {
        var dataId = $(this).attr("id");
        var $before = $("#basket > div").filter(function() {
            return $(this).attr("id") < dataId;
        });
        if ($before.length) {
            $before.last().after(this);
        } else {
            $("#basket").prepend(this);
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="basket">
    <div id="01" class="visible" data-owner="b">01-B-Visible</div>
    <div id="02" class="notvisible" data-owner="c">02-C-NotVisible</div>
    <div id="03" class="visible" data-owner="x">03-X-Visible</div>
    <div id="06" class="notvisible" data-owner="a">06-A-NotVisible</div>
    <div id="08" class="notvisible" data-owner="b">08-B-NotVisible</div>
</div>

<hr>

<div class="group" data-user-group="x"></div>
<div class="group" data-user-group="b"></div>

<button onclick="groupTheVisible()">Group the Visible</button>
<button onclick="regroupTheVisible()">Regroup the Visible</button>

注意:确保使用var(或letconst)声明您的变量,以避免它们成为全局变量。

NB2:当您移动元素时,实际上没有必要在它们上调用detach

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多