Randomize order of <a> links on page using jQuery
I have a list of links sitting inside a tag right now. I would like for the page to 'reorganize' the order of each link on page reload (page view) and display the results.
For example:
<div id="testgroup">
<a href="1.html" id="1">1</a>
<a hre开发者_开发百科f="2.html" id="2">2</a>
<a href="3.html" id="3">3</a>
<a href="4.html" id="4">4</a>
<a href="5.html" id="5">5</a>
</div>
On page reload, the soure code would look like:
<div id="testgroup">
<a href="5.html" id="5">5</a>
<a href="1.html" id="1">1</a>
<a href="3.html" id="3">3</a>
<a href="4.html" id="4">4</a>
<a href="2.html" id="2">2</a>
</div>
or some other random order
Is there a very basic jQuery DOM manipulation script to accomplish this? If it helps, the page is built on PHP as well.
If simplicity is more important than randomness:
You can use get
to convert the jQuery object to an array, then use the native sort
with a function designed to randomize it. Then put the randomly arranged array back into the DOM.
var array = $("#testgroup").children().get().sort( function() {
return 0.5 - Math.random();
});
$("#testgroup").append(array);
Demo: http://jsfiddle.net/4e7cs/
If you are looking for true shuffling:
You can utilize the Fisher-Yates shuffle:
var array = $("#testgroup").children().toArray();
var i = array.length,
j, temp;
while (--i) {
j = Math.floor(Math.random() * (i + 1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
$("#testgroup").append(array);
Demo: http://jsfiddle.net/4e7cs/3/
Here is a writeup on why the first is bad, but I'll leave it here for completeness.
PHP has a shuffle() function to randomize arrays. You can do the randomization on the server side.
<?php
$links = array(
1 => '1.html',
2 => '2.html',
3 => '3.html',
4 => '4.html',
5 => '5.html'
);
$shuffledLinks = shuffle_assoc($links);
foreach ($shuffledLinks as $value=>$key) {
echo '<a href="'.$key.'" id='.$value.'>'.$value.'</a><br/>';
}
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key)
$random[$key] = $list[$key];
return $random;
}
?>
Ok...this is now fixed and tested. Actually shuffle() did not work on associative arrays so I borrowed andjones at gmail dot com's shuffle_assoc() function for that.
I also mixed up my concatenation where I was using '+' instead of '.' O.o Mixing up my JavaScript and PHP syntax. I apologize about that.
Allen
I'm using a plugin that actualy does that : http://james.padolsey.com/javascript/sorting-elements-with-jquery/
But if you are using PHP you could sort it directly on the server?
精彩评论