简体   繁体   English

JQuery,如何按字母顺序重新排序 dom 元素?

[英]JQuery, how to reorder dom elements alphabetically?

I am displaying a list of checkboxes in a modal.我在模态中显示复选框列表。 The modal contents looks something like:模态内容如下所示:

<div class="container>
  <label>
    <input type="checkbox" name="A name" value="A Value">
    &nbsp;A Value
  </label>
  <br>
  <label>
    <input type="checkbox" name="B name" value="B Value">
    &nbsp;B Value
  </label>
  ....
<div>

The checkboxes are reorder-able.复选框可以重新排序。 But each time the modal gets displayed, I'd like to rest the order of the checkboxes so they display in alphabetic order.但是每次显示模态时,我想保持复选框的顺序,以便它们按字母顺序显示。 Sorting them is easy enough, using the below code, but any suggestions on how I can manipulate the container so that the checkboxes are in the proper order?使用下面的代码对它们进行排序很容易,但是关于如何操作容器以使复选框按正确顺序排列的任何建议?

var sorted = modal.find(':checkbox').sort(function(a, b) {

        var aText = a.value;
        aText = aText.trim().toLowerCase();

        var bText = b.value;
        bText = bText.trim().toLowerCase();


        if (aText < bText) {
          return -1;
        } else if (aText > bText) {
          return 1;
        } else {
          return 0;
        }
      });

Try this : use below code to rearrange your checkboxes.试试这个:使用下面的代码重新排列你的复选框。 (Assuming that your sort function is correct) (假设您的排序功能是正确的)

var sorted = modal.find(':checkbox').sort(function(a, b) {

        var aText = a.value;
        aText = aText.trim().toLowerCase();

        var bText = b.value;
        bText = bText.trim().toLowerCase();


        if (aText < bText) {
          return -1;
        } else if (aText > bText) {
          return 1;
        } else {
          return 0;
        }
      }).each(function (_, checkbox) {
              $(checkbox).closest('.container').append($(checkbox).closest('label'));
        });

JSFiddle Demo JSFiddle 演示

NOTE - Please move your <br> inside <label> tag注意- 请将您的<br>移到<label>标签内

First sort the labels:首先对标签进行排序:

var $sorted = modal.find('label:has(:checkbox)').sort(function(a, b) {
    var valA = $(a).find(':checkbox').val().trim().toLowerCase();
    var valB = $(b).find(':checkbox').val().trim().toLowerCase();
    return valA.localeCompare(valB);
});

Then add them again to the parent:然后将它们再次添加到父级:

$container.empty().append($sorted.after('<br />'));
var container = document.querySelector(".container");
sorted.forEach(function(chk) {
    var elementToMove = chk.parentElement; // move the label
    container.appendChild(elementToMove);
});

almost does it ... but those pesky < BR > spoil the deal几乎是这样......但是那些讨厌的<BR>破坏了交易

add添加

.container>label { display:block; }

to your CSS, and remove the < BR >到您的 CSS,并删除 <BR>

edit: I accidentally didn't jQuery on purpose编辑:我不小心没有故意使用 jQuery

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

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