简体   繁体   English

插入按字母顺序,javascript或jquery排序的新列表

[英]Insert new list sorted in alphabetical order, javascript or jquery

I have lists, already sorted alphabetically as below: 我有列表,已按字母顺序排序如下:

<ul>
  <li><a href='#'>Apple</a></li>
  <li><a href='#'>Banana</a></li>
  <li><a href='#'>Grapes</a></li>
<ul>

So i wanted to add new list which has the value of Chico so it should be inserted between Banana and Grapes ...like it will fade in. So i have a form or an input field to add a new list of fruits... 所以我想添加具有Chico值的新列表,所以它应该插入BananaGrapes之间...就像它会淡入。所以我有一个表单或输入字段来添加一个新的水果列表...

Is there any way to do that using jquery or javascript? 有没有办法用jquery或javascript做到这一点?

Thanks! 谢谢!

function sortAlpha(a,b){  
    return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;  
}

$("#insert").on('click', function() {
    var newLi = $("<li><a href='#'>"+$("#fruit").val()+"</a></li>").hide();
    $('li', 'ul').add(newLi.fadeIn(800)).sort(sortAlpha).appendTo('ul');
});​

FIDDLE 小提琴

See this working Fiddle Example ! 看到这个工作小提琴示例

This function adds the new list item to the provided list. 此函数将新列表项添加到提供的列表中。 After adding the new item, it will sort all items by their contents. 添加新项目后,它将按内容对所有项目进行排序。

function addNewListItem($list, $ele) {

    // append new element
    $list.append($ele);

    // get all elements
    var listItems = $list.children('li').get();

    // sort elements by contents
    listItems.sort(function(a, b) {
       return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
    });
    $.each(listItems, function(idx, itm) { $list.append(itm); });
}

Example usage: 用法示例:

//Creating a new item
var $newLI = $('<li/>').append($('<a/>', {"href":'#',"title":''}).html('Chico'));

// adding and sorting
addNewListItem($('ul'), $newLI);

Original sort function is credit to Dan @ onemoretake , via this stackoverflow answer. 通过 stackoverflow答案,原始排序功能是Dan @ onemoretake的功劳。

CSS CSS

.hide {
   display: none
}

jQuery jQuery的

function addListElement(el) {
    var lis = $('ul li').add(el).sort(function(a, b) {
        return $('a', a).text() > $('a', b).text();
    });

    $('ul').html(lis).find('.hide').fadeIn(3000, function() {
        $(this).removeClass('hide')
    });
}

addListElement('<li class="hide"><a href="#">Chico</a></li>');

Working sample 工作样本

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

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