luc*_*son 1 javascript jquery dom
I'm trying to take the contents of a list, that is not in alphabetical order, then by adding each item to an array, sort them into alphabetical order and insert them back into the list in alphabetical order.
Plain language: I need to alphabetize a list using JS or jQuery.
这就是我所拥有的。我只是不知道如何将数组的内容插入回列表中。
谢谢大家 :)
var sectors = [];
$("li").each(function() { sectors.push($(this).text()) });
sectors.sort();
console.log(sectors);Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<ul>
<li id="alphabet">B</li>
<li id="alphabet">C</li>
<li id="alphabet">A</li>
</ul>Run Code Online (Sandbox Code Playgroud)
这里不需要生成数组,可以sort()直接在选择li元素产生的jQuery对象上使用该方法。排序后,您可以ul按照更正的顺序将它们附加回父级。尝试这个:
$("li").sort(function(a, b) {
var aText = $(a).text(), bText = $(b).text();
return aText < bText ? -1 : aText > bText ? 1 : 0;
}).appendTo('ul');
Run Code Online (Sandbox Code Playgroud)
另请注意,id文档中具有重复属性是无效的。您的#alphabet元素应该改为使用 a class。
按正确顺序逐项移至末尾
// selector to parent element (best approach by id)
var parent = document.querySelector("ul"),
// take items (parent.children) into array
itemsArray = Array.prototype.slice.call(parent.children);
// sort items in array by custom criteria
itemsArray.sort(function (a, b) {
// inner text suits best (even when formated somehow)
if (a.innerText < b.innerText) return -1;
if (a.innerText > b.innerText) return 1;
return 0;
});
// reorder items in the DOM
itemsArray.forEach(function (item) {
// one by one move to the end in correct order
parent.appendChild(item);
});
Run Code Online (Sandbox Code Playgroud)它比 jQuery 快一百倍,查看性能比较图表http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/
| 归档时间: |
|
| 查看次数: |
4102 次 |
| 最近记录: |