How to swap element on screen with JavaScript

前端 未结 5 1535
你的背包
你的背包 2021-01-21 08:22

I have multiple \'li\' elements:

$(\".my_lis\")

with on the page I want to shuffle them around with JavaScript (I\'m using JQuery). How to do t

5条回答
  •  悲哀的现实
    2021-01-21 09:09

    It's not too hard actually. The general idea is:

    1. Grab all the dom nodes
    2. Shuffle them
    3. Empty the
        and insert the shuffled nodes

    --

    var items = $('.my_list li').get();
    
    //edit (per comments): avoid confusion
    items = shuffle(items);
    
    $('.my_list').empty().append(items);
    

    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:

    Just an example on shuffling ANY array

    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;
    }
    

提交回复
热议问题