[英]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
值的新列表,所以它应该插入Banana
和Grapes
之间...就像它会淡入。所以我有一个表单或输入字段来添加一个新的水果列表...
Is there any way to do that using jquery or javascript? 有没有办法用jquery或javascript做到这一点?
Thanks! 谢谢!
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>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.