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
精彩评论