问题
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