本文介绍了javascript随机选择变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何让javascript在两个按钮之间随机选择点击?
How can I make javascript randomly choose between two buttons to click?
var $1Button = $('#1'),
$2Button = $('#2');
function startQuiz(){
$1Button.trigger('click');
}
推荐答案
处理这种情况的一种简单方法是将两个按钮放在一个数组中,然后在该数组中随机选择一个索引来触发点击.作为一个额外的好处,代码可以轻松扩展到两个以上的按钮.
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');
}
这篇关于javascript随机选择变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!