如何使用JavaScript交换屏幕上的元素 [英] How to swap element on screen with JavaScript
本文介绍了如何使用JavaScript交换屏幕上的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个"li"元素:
I have multiple 'li' elements:
$(".my_lis")
在页面上,我想用JavaScript(我正在使用JQuery)将它们随机播放.该怎么做?
with on the page I want to shuffle them around with JavaScript (I'm using JQuery). How to do that?
推荐答案
实际上并不难.总体思路是:
It's not too hard actually. The general idea is:
- 获取所有dom节点
- 随机播放
- 清空
<ul>
并插入经过改组的节点
- Grab all the dom nodes
- Shuffle them
- Empty the
<ul>
and insert the shuffled nodes
-
var items = $('.my_list li').get();
//edit (per comments): avoid confusion
items = shuffle(items);
$('.my_list').empty().append(items);
其中shuffle()可以是对数组进行混洗的任何内容,我更喜欢underscore.js,但这是一种在数组上进行混洗的原始JavaScript方法:
Where shuffle() can be anything that shuffles the array, I prefer underscore.js but here is a vanilla JavaScript way of doing a shuffle on an Array:
仅是改组ANY数组的示例
function shuffle(items) {
for(var index = 0, ln = items.length; index < ln; index++) {
var item = items[index],
swapIndex = ~~(Math.random() * ln),
swapItem = items[swapIndex];
//Swap places
items.splice(swapIndex, 1, item);
items.splice(index, 1, swapItem);
}
return items;
}
这篇关于如何使用JavaScript交换屏幕上的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文