4

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...

Is there any way to do that using jquery or javascript?

Thanks!

4

3 回答 3

4
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');
});​

小提琴

于 2012-07-16T17:57:35.720 回答
2

请参阅此工作小提琴示例

此函数将新列表项添加到提供的列表中。添加新项目后,它将按内容对所有项目进行排序。

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); });
}

示例用法:

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

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

通过这个stackoverflow 答案,原始排序功能归功于Dan @ onemoretake 。

于 2012-07-16T18:03:02.213 回答
1

CSS

.hide {
   display: none
}

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>');

工作样本

于 2012-07-16T17:45:31.997 回答