如何根据他们的ID对LI进行排序 [英] How to sort LI's based on their ID

查看:189
本文介绍了如何根据他们的ID对LI进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试一堆解决方案,但没有可行的结果。我有代码获取跨度的值并为LI创建一个ID。然后我想根据LI的ID对这些LI的DESCENDING进行排序。帮帮我?谢谢!

 <!DOCTYPE html> 
< html>
< head>
< / head>
< body>
< ul id =dumb>
< li>大提琴< span> 2987< / span>< / li>
< li> zello< span> 1723< / span>< / li>
< li> aello< span> 3476< / span>< / li>
< / ul>
< script type ='text / javascript'src ='JQUERY INCLUDE'>< / script>
< script type =text / javascript>
$(document).ready(function(){
$('ul li span')。each(function(){
var pubValue = $(this).html();
$(this).parent()。attr('id',pubValue);
});
});
< / script>
< / body>
< / html>


解决方案

假设您的 li节点有ID。

 < ul id =test> 
< li id =4112> blub< / li>
< li id =1422> blaaah< / li>
< li id =6640> hmmmm< / li>
< li id =2221>多一个< / li>
< / ul>

然后你可以调用javascripts native array .sort()方法,因为jQuery包装集保存在数组中

 <$ c $ ($())$($)$()函数(){
var elems = $('#test')。children('li')。remove();
elems.sort(function(a,b){
return parseInt(a.id)> parseInt(b.id);
});
$('#test')。append(elems);
});

工作示例: http://www.jsfiddle.net/3uYUq/


Trying a bunch of solutions with no workable results. I have code that takes the value of the span and creates an ID for the LI. I then want to sort these LI's DESCENDING based on the LI's ID. Help? Thanks!

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul id="dumb">
    <li>cello<span>2987</span></li>
    <li>zello<span>1723</span></li>
    <li>aello<span>3476</span></li>
</ul>
<script type='text/javascript' src='JQUERY INCLUDE'></script> 
<script type="text/javascript"> 
$(document).ready(function() {
    $('ul li span').each(function(){
        var pubValue = $(this).html();
        $(this).parent().attr('id', pubValue);
    });
});
</script>
</body>
</html>

解决方案

Let's assume your li nodes had ids.

<ul id="test">
   <li id="4112">blub</li>
   <li id="1422">blaaah</li>
   <li id="6640">hmmmm</li>
   <li id="2221">one more</li>
</ul>

Then you could just call javascripts native array .sort() method, since jQuery wrapped sets are hold in Arrays:

$(function(){
    var elems = $('#test').children('li').remove();
    elems.sort(function(a,b){
        return parseInt(a.id) > parseInt(b.id);
    });
    $('#test').append(elems);
});

Working example: http://www.jsfiddle.net/3uYUq/

这篇关于如何根据他们的ID对LI进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆