Select random <li> element

泪湿孤枕 提交于 2019-12-08 04:57:22

问题


I'm trying to make a shuffle button for my HTML 5 player. My player is set up like this to go the next track:

    $('.nextbutton').on("click", function(){
    var next = $('li.playing').next();
        if (!next.length) next = $('#stuff ul li').first();
        next.addClass('playing').siblings().removeClass('playing');
        var title = $('a#tunes img', next).attr("title");
            $("a.songtitle span").text(title);
        var artist = $('a#tunes img', next).attr("artist");
            $("a.songartist span").text(artist);
        audio.load($('a#tunes', next).attr('data-src'));
        audio.play();
    });

This code works to go to the next song but how can I change this to make it so it selects a random <li> element instead of the .next(); <li>? Thanks for your time and consideration. Hope you can help me!


回答1:


var next = Math.floor(Math.random() * jQuery('#stuff ul li').length + 1));
var nextLi = jQuery('#stuff ul li').get(next);

It'll get random number between 0 and count of lis and then get this li.




回答2:


you can use a random number generator like

var rand =  Math.floor(Math.random() * jQuery('#stuff ul li').length + 1);

or

var rand =  Math.ceil(Math.random() *( jQuery('#stuff ul li').length + 1));

for getting a random song number in the list , and then get the corresponding item like this:

var next = $('#stuff ul li').get(rand);


来源:https://stackoverflow.com/questions/19352358/select-random-li-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!