jQuery如何实现已上树的dom元素随机排序?

https://img2.mukewang.com/5c836cf600017d4b02050392.jpg

上面的代码,目前p标签在game-box中是固定顺序排列的,我想实现每次刷新页面p的排列顺序都不一样,尤其是开头和结尾。目前我找到了一种不太好的方法,但是第一个元素经常不是9就是10,和我要的不一样。


//这个方法不够好

$(".game-box p").each(function(){

    if(Math.random() <= 0.5){

        $(this).prependTo($(this).parent());            

    }

})

请问有没有更好的思路呢?

如果是下面的table tr td应该怎么做呢?

https://img2.mukewang.com/5c836d030001d7e502550398.jpg

桃花长相依
浏览 405回答 2
2回答

jeck猫

// 获取DOM元素var $game_box = $('.game-box'),&nbsp; &nbsp; $game_box_list = $('.game-box p');// 列表乱序后添加到game_box$game_box.html(arrayRandomSort($game_box_list));// 数据乱序方法function arrayRandomSort(array) {&nbsp; &nbsp; var index = array.length;&nbsp; &nbsp; //开始遍历&nbsp; &nbsp; for (var i = array.length; i > 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; var random = parseInt(Math.random() * index);&nbsp; &nbsp; &nbsp; &nbsp; index--;&nbsp; &nbsp; &nbsp; &nbsp; //交换位置&nbsp; &nbsp; &nbsp; &nbsp; var last = array[index];&nbsp; &nbsp; &nbsp; &nbsp; array[index] = array[random];&nbsp; &nbsp; &nbsp; &nbsp; array[random] = last;&nbsp; &nbsp; }&nbsp; &nbsp; return array;}我的思路是,把获取到的DOM数组乱序后再放到game-box下。// 获取DOM元素var $table = $('table'),&nbsp; &nbsp; $tr_list = $('table tr'),&nbsp; &nbsp; $td_list = $('table tr td');// 生成乱序的td列表var random_list = arrayRandomSort($td_list);// 获取每一行的td数量var row_count = [];$tr_list.each((i, el) => {&nbsp; &nbsp; row_count.push($(el).find('td').length);});// 根据每一行td的数量显示$tr_list.each((i, el) => {&nbsp; &nbsp; $(el).html(random_list.splice(0, row_count[i]));});// 数据乱序方法function arrayRandomSort(array) {&nbsp; &nbsp; var index = array.length;&nbsp; &nbsp; //开始遍历&nbsp; &nbsp; for (var i = array.length; i > 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; var random = parseInt(Math.random() * index);&nbsp; &nbsp; &nbsp; &nbsp; index--;&nbsp; &nbsp; &nbsp; &nbsp; //交换位置&nbsp; &nbsp; &nbsp; &nbsp; var last = array[index];&nbsp; &nbsp; &nbsp; &nbsp; array[index] = array[random];&nbsp; &nbsp; &nbsp; &nbsp; array[random] = last;&nbsp; &nbsp; }&nbsp; &nbsp; return array;}这个应该就是你想要的效果
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript