我想从随机选择中选择一个选项。
<select class=".sel" id="sel">
    <option>a</option>
    <option>b</option>
    <option>c</option>
    <option>d</option>
</select>实际上,我使用的是jQuery自动完成。
那么,问题是我如何从选择框中随机选择选项?
我尝试的是
function change_something(opt)
    {
    var randomOption=Math.floor(Math.random()*$(opt+' option').size());
    $(opt+ option["value='"+randomOption+"'"]).attr('selected', 'selected');
  }实际上,我不是jQuery专家,所以我无法改变一些东西。
发布于 2012-03-06 12:16:34
像这样的东西应该是有效的:
var $options = $('#sel').find('option'),
    random = ~~(Math.random() * $options.length);
$options.eq(random).prop('selected', true);http://jsfiddle.net/elclanrs/8DPMN/
发布于 2012-03-06 12:15:30
这就是你需要的
options = $("#sel > option")
options[Math.floor(Math.random() * options.length)].selected = true另外,使用class="sel“代替class=".sel”
发布于 2012-03-06 12:12:19
这将适用于您的HTML示例代码片段。
var options = $("#sel > option");
var random = Math.floor(options.length * (Math.random() % 1));
$("#sel > option").attr('selected',false).eq(random).attr('selected',true);https://stackoverflow.com/questions/9577747
复制相似问题