javascript random pick variable

孤者浪人 提交于 2021-02-17 05:35:42

问题


How can I make javascript randomly choose between two buttons to click?

var $1Button = $('#1'),
    $2Button = $('#2');

function startQuiz(){
  $1Button.trigger('click');
}

回答1:


An easy way to handle this situation is to place your two buttons in an array and pick a random index in that array to trigger the click. As an added bonus, the code will easily expand to more than two buttons.

var $buttons = [$('#1'), $('#2')];

function startQuiz(){
  var buttonIndex = Math.floor(Math.random() * $buttons.length)
  $buttons[buttonIndex].trigger('click');
}



回答2:


You will need a function that can basically flip a coin and give you a 0 or 1, true or false, etc. It would probably be easiest to build an array of your elements, generate a random array index, find the element in the array and then trigger the click:

var buttons = [$('#1'), $('#2')];

function getRandomButton() {
    return buttons[Math.floor(Math.random() * buttons.length)];
}

function startQuiz(){
    getRandomButton().trigger('click');
}


来源:https://stackoverflow.com/questions/41656802/javascript-random-pick-variable

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