用戶端排序–jquery排序

來源:互聯網
上載者:User

前天,同事問我,jquery可不可以排序,我就有點發矇,我說你在伺服器端排吧,linq排起來很容易的,不過被否決了。(不過最終還是linq排的,但那是後話,下次說怎麼做)

我就google了下,別說,還真有,我就想嘛,jquery的迭代器那麼強大,怎麼也會有能排序的。

具體哪裡找的忘記了,不過作者的地址還有http://github.com/razorjack/jquery.sorted

body裡的內容很簡單:

    <div>
<ul>
<li data-id="9">one</li>
<li data-id="8">two</li>
<li data-id="7">three</li>
</ul>
<input type="button" value="排序" />
</div>

然後是指令碼了,這個是排序的指令碼,我放到了一個js檔案裡

/*

jquery.sorted - super simple jQuery sorting utility

Copyright (c) 2010 Jacek Galanciak

Dual licensed under the MIT and GPL version 2 licenses.

http://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt

http://github.com/jquery/jquery/blob/master/GPL-LICENSE.txt

Github/docs site: http://github.com/razorjack/jquery.sorted

*/

(function ($) {
$.fn.sorted = function (customOptions) {

var options = {
reversed: false,
by: function (a) { return a.text(); }
};

$.extend(options, customOptions);

$data = $(this);
arr = $data.get();
arr.sort(function (a, b) {
var valA = options.by($(a));
var valB = options.by($(b));
if (options.reversed) {
return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;
} else {
return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;
}
});
return $(arr);
};
})(jQuery);

下面是引入指令檔:

<script src="http://www.cnblogs.com/Scripts/jquery-1.4.4-vsdoc.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/JScript1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(function () {
$("input").click(function () {

for (i = 0; i < $("ul li").sorted().length; i++) {
alert($("ul li").sorted().eq(i).html());
}
});
});
</script>
</head>

其實我一開始想的是,直接就排序了,不過最後發現不是這樣,而是把結果存到了對象裡,自己去取,呵呵。

具體的東西其實一試就知道了。這東西挺有意思的,或許用處不大,不過我想說的是,牛人真多啊。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.