开发者

jQuery / PHP - sort html list by PHP array values?

开发者 https://www.devze.com 2023-01-05 21:16 出处:网络
I have a list like this: <li> <input value=\"1\" name=\"bla[]\" /> </li> <li> <input value=\"2\" name=\"bla[]\" /> </li>

I have a list like this:

<li> <input value="1" name="bla[]" /> </li>
<li> <input value="2" name="bla[]" /> </li>
<li> <input value="3" name="bla[]" /> </li>

(always the same order)

and a array like this

array('3', '1', '2');

but the order of the values in the array can change anytime. Can the list above be sorted with jQuery based on the a开发者_开发技巧rray order?


You can do it client-side like this, if PHP isn't an option (please do it in PHP if possible, no need for JavaScript in that case):

var arr = ['3', '1', '2'];
for(var i=0; i<arr.length; i++) {
    $("ul li input[value='" + arr[i] + "']").parent().appendTo("ul");
}​

You can see a demo here


Though if you don't actually need to sort, can't you just set those values on the inputs in a loop? This assumes the real code isn't a lot more complex than the example, like this:

var arr = ['3', '1', '2'];
$("ul li input").val(function(i) {
    return arr[i];
});​

You can try that version here


You'll want to use javascript for this, but close enough to jQuery I suppose!

You can implement the sort() method. See here: http://www.w3schools.com/jsref/jsref_sort.asp

And if you need to sort with PHP see here: http://php.net/manual/en/function.sort.php

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号