My plugin version - Working Demo
Takes an array and optional id prefix and reorders elements whose ids correspond to the order of (id prefix) + values inside the array. Any values in the array that don't have an element with the corresponding id will be ignored, and any child elements that do not have an id within the array will be removed.
(function($) {
$.fn.reOrder = function(array, prefix) {
return this.each(function() {
prefix = prefix || "";
if (array) {
for(var i=0; i < array.length; i++)
array[i] = $('#' + prefix + array[i]);
$(this).empty();
for(var i=0; i < array.length; i++)
$(this).append(array[i]);
}
});
}
})(jQuery);
Code from the demo
jQuery
$(function() {
$('#go').click(function() {
var order = $('#order').val() == ""? null: $('#order').val().split(",");
$('#container').reOrder(order, 'someid');
});
});
(function($) {
$.fn.reOrder = function(array, prefix) {
return this.each(function() {
prefix = prefix || "";
if (array) {
for(var i=0; i < array.length; i++)
array[i] = $('#' + prefix + array[i]);
$(this).empty();
for(var i=0; i < array.length; i++)
$(this).append(array[i]);
}
});
}
})(jQuery);
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>reOrder Demo</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; }
div.style { width: 200px; height: 100px; border: 1px solid #000000; margin: 5px; }
</style>
</head>
<body>
<div id="container">
<div id="someid1" class="style" style="background-color:green;">div1</div>
<div id="someid2" class="style" style="background-color:blue;">div2</div>
<div id="someid3" class="style" style="background-color:red;">div3</div>
<div id="someid4" class="style" style="background-color:purple;">div4</div>
</div>
<p>Pass in a comma separated list of numbers 1-4 to reorder divs</p>
<input id="order" type="text" />
<input id="go" type="button" value="Re-Order" />
</body>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…