Sorting li elements by class with jQuery

时光怂恿深爱的人放手 提交于 2019-12-22 08:30:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!