问题
I'd like to reorder li elements through an array with jQuery
My list code looks like this:
<html>
<head>
<script src="list.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="list">
<ul class="xyz">
<li class="element1">content for 1</li>
<li class="element2">content for 2</li>
<li class="element3">content for 3</li>
</ul>
</div>
</body>
</html>
I now want to reorder the DOM elements through an array.
I tried, but I don't get it running:
var array = ['element2', 'element1', 'element3'];
$.each(array,function(index,value){
$('.xyz').append($(value));
});
回答1:
You missed a .
- to select a DOM element with a class
you must use .
- see the class selector docs
var array = ['element2', 'element1', 'element3'];
$.each(array,function(index,value){
$('.xyz').append($('.'+value)); // add . here
});
Alternatively you could add the .
to the array
Working example here
回答2:
I would get the inner HTML of each li
into an array, empty the ul
of elements, then repopulate the ul
with the sorted items of the array created in the first step.
来源:https://stackoverflow.com/questions/10109656/sorting-li-elements-by-class-with-jquery