简体   繁体   English

怎么排序 <ul><li> 基于javascript的课程?

[英]How to sort <ul><li>'s based on class with javascript?

I have a TODO list app with an Unordered list. 我有一个带有无序列表的TODO列表应用程序。 Within it I have a few list items. 在其中我有几个列表项。 The li classes are high,medium,low. 李班高,中,低。 I would like li's with the class high to be placed before li's with the class medium and last ones with low. 我希望李的高级课程可以放在李先生的班级中,而最后的班级则低。

<ul id="tasks">
  <li id="item3" class="priority low"><span></span><a href="#" class="closex" onclick="removeItem('item3')"></a><span>This is a low priority task</span></li>
  <li id="item4" class="priority high"><></span><a href="#" class="closex" onclick="removeItem('item4')"></a><span>This is a high priority task</span></li>
  <li id="item5" class="priority low"><span></span><a href="#" class="closex" onclick="removeItem('item5')"></a><span>This is another Low</span></li>
  <li id="item7" class="priority medium"><span></span><a href="#" class="closex" onclick="removeItem('item7')"></a><span>And now a Medium</span></li>
</ul>

So the li with id of item4 should be first and then it should be item7 and then the li's with class low after. 因此,id为item4的li应该是第一个,然后它应该是item7,然后是具有类低的li。

Here's a pure JS version of @ŠimeVidas jQuery solution. 这是@ŠimeVidasjQuery解决方案的纯JS版本。

var tasks = document.querySelector('#tasks'),
    items = document.querySelectorAll('#tasks > li');

for (var i = 0, arr = ['high', 'medium', 'low']; i < arr.length; i++) {
    for (var j = 0; j < items.length; j++) {
        if (~(" " + items[j].className + " ").indexOf(" " + arr[i] + " "))
            tasks.appendChild(items[j]);
    }
}

Assuming you can use jQuery, and assuming your list is not very big, and assuming you've only got these three fixed types with no plans on changing this, I'd probably just dump the whole set into memory, clear out the list, then put them back in the list in order. 假设你可以使用jQuery,并假设你的列表不是很大,假设你只有这三种固定类型而没有改变它的计划,我可能只是将整个集合转储到内存中,清除列表,然后按顺序将它们放回列表中。 Something like: 就像是:

jQuery(document).ready(function() {
    var i;
    var items = jQuery("#tasks li");
    var lowItems = [];
    var medItems = [];
    var highItems = [];
    for (i = 0; i < items.length; ++i) {
        var jqItem = jQuery(items[i]);
        if (jqItem.hasClass("low")) lowItems.push(jqItem);
        if (jqItem.hasClass("medium")) medItems.push(jqItem);
        if (jqItem.hasClass("high")) highItems.push(jqItem);
    }
    var tasks = jQuery("#tasks");
    tasks.html("");
    for (i = 0; i < highItems.length; ++i) {
        tasks.append(highItems[i]);
    }   
    for (i = 0; i < medItems.length; ++i) {
        tasks.append(medItems[i]);
    }   
    for (i = 0; i < lowItems.length; ++i) {
        tasks.append(lowItems[i]);
    }
});

Try this: 尝试这个:

$(function(){
    var sorter = [],
        tasks = $('#tasks');
    $('li.priority').each(function(){
        var $this = $(this),
            priority = $this.hasClass('high') ? 3 : ($this.hasClass('medium') ? 2 : 1);
        sorter.push({
            el : this,
            priority : priority
        });
    }).detach();

    sorter.sort(function(a, b){
        return a.priority - b.priority;
    });

    $.each(sorter, function(){
        tasks.append(this.el);
    });
});

With no jquery: 没有jquery:

<ul id="tasks">
 <li id="item3" class="priority low"><span></span><a href="#" class="closex" onclick="removeItem('item3')"></a><span>This is a low priority task</span></li>
 <li id="item4" class="priority high"><></span><a href="#" class="closex" onclick="removeItem('item4')"></a><span>This is a high priority task</span></li>
 <li id="item5" class="priority low"><span></span><a href="#" class="closex" onclick="removeItem('item5')"></a><span>This is another Low</span></li>
 <li id="item7" class="priority medium"><span></span><a href="#" class="closex" onclick="removeItem('item7')"></a><span>And now a Medium</span></li>
</ul>

<script type="text/javascript">
var tasks = document.getElementById("tasks");
var liElements = tasks.getElementsByTagName("li");
var lowPriority = [];
var mediumPriority = [];
var highPriority = [];
var removal = [];
for (var i = 0, len = liElements.length; i < len; i++) {
    if (liElements[i].getAttribute("class").indexOf("low") > -1) lowPriority.push(liElements[i].cloneNode(true));
    if (liElements[i].getAttribute("class").indexOf("medium") > -1) mediumPriority.push(liElements[i].cloneNode(true));
    if (liElements[i].getAttribute("class").indexOf("high") > -1) highPriority.push(liElements[i].cloneNode(true));
    removal.push(liElements[i]);
}

for (var i = 0, len = removal.length; i < len; i++ ) {
    var liItem = removal[i];
    liItem.parentNode.removeChild(liItem);
}

for( var i = 0, len = lowPriority.length; i < len; i++){
    tasks.appendChild(lowPriority[i]);
}
for (var i = 0, len = mediumPriority.length; i < len; i++) {
    tasks.appendChild(mediumPriority[i]);
}
for (var i = 0, len = highPriority.length; i < len; i++) {
    tasks.appendChild(highPriority[i]);
}
</script>

Here's another jQuery–less option: 这是另一个jQuery-less选项:

// Just a helper
function toArray(obj) {
  var result = [];
  for (var i=0, iLen=obj.length; i<iLen; i++) {
    result[i] = obj[i];
  }
  return result;
}

// Uses querySelectorAll, but could use getElementsByTagName instead
function sortByPriority(id) {
  var nodes;
  var el = document.getElementById(id);

  if (el) { 
    nodes = toArray(el.querySelectorAll('li.priority'));
    nodes.sort(function(a, b) {
      function getIndex(el) {
        return el.className.indexOf('low') != -1? 1 : 
               el.className.indexOf('medium') != -1? 2 :
               el.className.indexOf('high') != -1? 3 :
               0; // default
      }
      return getIndex(b) - getIndex(a);
    });

    for (var i=0, iLen=nodes.length; i<iLen; i++) {
      el.appendChild(nodes[i]);
    }
  }
}

It uses a few more lines that a jQuery (or perhaps any library) based solution but you don't have to load several thousand lines of library either. 它使用了一些基于jQuery(或者可能是任何库)的解决方案,但你不必加载几千行库。

Also, this runs about 5 times faster in Firefox and IE 9 and 10 times faster in Chrome than a jQuery solution (see http://jsperf.com/sortelementlist ). 此外,它在Firefox和IE 9中运行速度提高了约5倍,在Chrome中运行速度比jQuery解决方案快10倍(请参阅http://jsperf.com/sortelementlist )。

With pure JavaScript, and simple code! 使用纯JavaScript和简单的代码!

var tasks = document.getElementById("tasks");
var lis = tasks.getElementsByTagName("li");
var lisarr = Array.prototype.slice.call(lis);

var priority = function(e){
    var prio = {low: 0, medium: 1, high: 2};
    return prio[e.getAttribute("class").match(/low|high|medium/)[0]];
};

lisarr.sort(function(a,b){
    var ap = priority(a), bp = priority(b);
    return bp - ap;
});

tasks.innerHTML = lisarr.reduce(function(prev, current){
    return prev + current.outerHTML;
}, '');

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

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