Перемешивание листа в jquery?

Привет хабр, есть такая конструкция

<ul><br>
<li id="1">lorum</li><br>
<li id="2">ipsum</li><br>
<li id="3">beta</li><br>
</ul>




Можно ли как нибудь в случайном порядке перемешать этот список так, чтобы id так и оставались в порядке возрастания, а значения перемешивались, например:



<ul><br>
<li id="1">beta</li><br>
<li id="2">ipsum</li><br>
<li id="3">lorum</li><br>
</ul>
  • Вопрос задан
  • 3901 просмотр
Решения вопроса 1
xel
@xel
front end developer
Наверное правильнее всего будет оформить как функцию jquery.
Перемешивать любые коллекции можно.

(function($){
$.fn.shuffle = function() {
return this.each(function(){
var items=$(this).children().map(function(){return $(this).contents()}).get();
items.sort(function(){ return 0.5 - Math.random() });
$(this).children().map(function(){$(this).empty().append(items.pop())});
return $(this);
});
}
})(jQuery);


Использовать $('ul').shuffle()
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
k12th
@k12th
console.log(`You're pulling my leg, right?`);
function randSign() { return 0.5 - Math.random() }
// ...
$(function() {
    var values = [],
        items = $('ul li');
        
    items.each(function(index) {
        values.push( items.eq(index).text() )
    })
    
    values.sort(randSign)
    
    items.each(function(index) {
        items.eq(index).text( values[index] )
    })
})
Ответ написан
woid
@woid
Самый простой вариант, на мой взгляд.

<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('#button').click(function(){
            var randomize = function(arr){
                var length = arr.length - 1;
                for (var i = 0; i <= length; i++){
                    var rnd1 = Math.round(Math.random()*length),
                          rnd2 = 0;
                    do{
                        rnd2 = Math.round(Math.random()*length);
                    } while (rnd1 == rnd2);
                    var tmp = arr[rnd1];
                    arr[rnd1] = arr[rnd2];
                    arr[rnd2] = tmp;
            }
        }
        var items = [];
        //заполняем массив содержимым списка
        $('ul li').each(function(){
            items.push($(this).html());
        });
        //перемешиваем
        randomize(items);
        //обновляем список
        var length = items.length;
        for (var i = 0; i < length; i++){
            $($('ul li')[i]).html(items[i]); //возможно, это можно сделать как-то иначе
        }
    });
});
</script>
</head>
<body>
<ul>
<li id="1">lorum</li>
<li id="2">ipsum</li>
<li id="3">beta</li>
</ul>

<input type="button" id="button" value="Click me"/>
</body>
</html>
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы