按字母顺序排序表并进行分类

时间:2015-02-03 23:58:48

标签: jquery html sorting

您好我正在尝试制作表格列表,排序和整理。 我理想的设置将是一个表格,我只需要输入名称,然后将它们组织起来并将它们放在正确的类别中。 以 A 开头的名称将放在 A类别中,而以 B 开头的名称将放入 B类依此类推。

我的第一张图片显示了我想要的内容(未排序,只是一个示例)。 我的第二张图片展示了在使用我在其他帖子上找到的JQuery代码时得到的结果,我搜索并发现没有涉及分类的示例。

JSFiddle 第二张照片来自这个小提琴的结果。

这是我用于排序的JQuery函数

    var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function (a, b) {
    return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
 $.each(listitems, function (idx, itm) {
    mylist.append(itm);
});

enter image description here

enter image description here

谢谢,所有投入都非常赞赏。

1 个答案:

答案 0 :(得分:1)

我不禁觉得应该有更好的方法,但这是我能想到的最好的方法,目前(虽然它使用的是原生JavaScript,而不是jQuery):

// retrieves the first <ul> from the document:
var mylist = document.querySelector('ul'),
    // retrieves the <li> children from that <ul>,
    // using Function.prototype.call, and Array.prototype.slice
    // to convert that NodeList into an Array:
    listitems = Array.prototype.slice.call(mylist.querySelectorAll('li'), 0),
    // an empty object, for later use:
    order = {},
    // elements, for later use:
    ul = document.createElement('ul'),
    li = document.createElement('li'),
    // a document fragment:
    fragment = document.createDocumentFragment(),
    // the assigned width for the sorted lists (adjust to taste):
    width = 100,
    // the offset (to set the node.style.left CSS property):
    offset = 0,
    // empty variables for use later:
    first,
    cloneUL,
    cloneLI;

// your original sort function, but using plain JavaScript, using
// node.textContent in place of jQuery's $(node).text()
listitems.sort( function (a, b) {
    return a.textContent.toUpperCase().localeCompare(b.textContent.toUpperCase());
// chaining Array.prototype.forEach() to perform an action on
// each element of the sorted array:
}).forEach(function (li, index, arr) {
    // li: the first argument of the anonymous function is
    // is always the array-element (in this case the <li>),
    // index: the second argument is the index of the current
    // array-element (here unused),
    // arr: the third argument is the full array over which
    // we're iterating (here unused).

    // storing a reference to the first letter of the current <li>:
    first = li.textContent.charAt(0);

    // if there is no value for a given key (first) for the object
    // (order), we...
    if (!order[first]) {
        // ...create an empty array:
        order[first] = [];
    }

    // and then push the current <li> into that array:
    order[first].push(li);        
});

// here we use the for...in loop to iterate over the
// (not reliably ordered) properties of the array:
for (var letter in order){
    // using Object.prototype.hasOwnProperty() to
    // check that the current property (the letters, from
    // earlier) has been assigned deliberately (true) or
    // inherited from the prototype chain (false):
    if (order.hasOwnProperty(letter)){
        // cloning the li (from earlier) and
        // assigning it to the empty variable:
        cloneLI = li.cloneNode();
        // as above, with different variables:
        cloneUL = ul.cloneNode();

        // assigning the id of the created/cloned-<ul>:
        cloneUL.id = letter;

        // setting the left and width properties:
        cloneUL.style.left = offset + 'px';
        cloneUL.style.width = width + 'px';

        // appending the cloned-<ul> to the cloned-<li>:
        cloneLI.appendChild(cloneUL);

        // iterating over the sorted array of <li> elements
        // stored in the order[letter] properties:
        order[letter].forEach(function (li) {
            // appending each <li> in turn to the cloned-<ul>:
            cloneUL.appendChild(li);
        });

        // appending the cloned-<li> (containing the cloned-<ul>)
        // the created documentFragment:
        fragment.appendChild(cloneLI);

        // updating the offset, to prevent overlap of
        // the created-<li> elements:
        offset += width;
    }
}

// while the <ul> (mylist) has a firstChild:
while (mylist.firstChild) {
    // we remove that firstChild:
    mylist.removeChild(mylist.firstChild);
}
// appending the created-documentFragment to the
// now emptied <ul>:
mylist.appendChild(fragment);

var mylist = document.querySelector('ul'),
  listitems = Array.prototype.slice.call(mylist.querySelectorAll('li'), 0),
  order = {},
  ul = document.createElement('ul'),
  li = document.createElement('li'),
  fragment = document.createDocumentFragment(),
  width = 100,
  offset = 0,
  first,
  cloneUL,
  cloneLI;

listitems.sort(function(a, b) {
  return a.textContent.toUpperCase().localeCompare(b.textContent.toUpperCase());
}).forEach(function(li) {
  first = li.textContent.charAt(0);
  if (!order[first]) {
    order[first] = [];
  }
  order[first].push(li);
});

for (var letter in order) {
  if (order.hasOwnProperty(letter)) {
    cloneLI = li.cloneNode();
    cloneUL = ul.cloneNode();
    cloneUL.id = letter;

    cloneUL.style.left = offset + 'px';
    cloneUL.style.width = width + 'px';

    cloneLI.appendChild(cloneUL);
    order[letter].forEach(function(li) {
      cloneUL.appendChild(li);
    });
    fragment.appendChild(cloneLI);
    offset += width;
  }
}

while (mylist.firstChild) {
  mylist.removeChild(mylist.firstChild);
}
mylist.appendChild(fragment);
body {
  padding: 0;
}
ul,
li {
  list-style-type: none;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
ul {
  display: block;
}
ul > li {
  display: inline-block;
  position: relative;
}
ul > li > ul {
  display: list;
  position: absolute;
  top: 0;
}
ul > li > ul > li {
  display: list-item;
}
li:nth-child(odd) > ul {
  background-color: #ffa;
}
li:nth-child(even) > ul {
  background-color: #f00;
}
<ul>
  <li>Ape</li>
  <li>Ace</li>
  <li>Ache</li>
  <li>Aart</li>
  <li>Ant</li>
  <li>A1</li>
  <li>Bear</li>
  <li>Beat</li>
  <li>Born</li>
  <li>Corpse</li>
  <li>Carp</li>
  <li>Cant</li>
  <li>Crane</li>
  <li>Crazy</li>
  <li>Computer</li>
</ul>

JS Fiddle demo,以促进实验。

参考文献:

相关问题