Red*_*Red 0 html javascript jquery html-select
我想从随机选择中选择一个选项.
<select class=".sel" id="sel">
<option>a</option>
<option>b</option>
<option>c</option>
<option>d</option>
</select>
Run Code Online (Sandbox Code Playgroud)
实际上我正在使用jQuery自动完成.
那么,问题是如何从选择框中随机选择选项?
我试过的是
function change_something(opt)
{
var randomOption=Math.floor(Math.random()*$(opt+' option').size());
$(opt+ option["value='"+randomOption+"'"]).attr('selected', 'selected');
}
Run Code Online (Sandbox Code Playgroud)
实际上我不是一个jQuery专家,所以我没有改变一些东西.
这样的事情应该有效:
var $options = $('#sel').find('option'),
random = ~~(Math.random() * $options.length);
$options.eq(random).prop('selected', true);
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/elclanrs/8DPMN/
这就是你需要的
options = $("#sel > option")
options[Math.floor(Math.random() * options.length)].selected = true
Run Code Online (Sandbox Code Playgroud)
另外,使用 class="sel" 而不是 class=".sel"