jquery / javascript随机选择选项

我想从随机选择中选择一个选项。

 a b c d  

实际上我正在使用jQuery自动完成。

那么,问题是如何从选择框中随机选择选项?

我试过的是

 function change_something(opt) { var randomOption=Math.floor(Math.random()*$(opt+' option').size()); $(opt+ option["value='"+randomOption+"'"]).attr('selected', 'selected'); } 

实际上我不是一个jQuery专家,所以我没有改变一些东西。

像这样的东西应该工作:

 var $options = $('#sel').find('option'), random = ~~(Math.random() * $options.length); $options.eq(random).prop('selected', true); 

http://jsfiddle.net/elclanrs/8DPMN/

这就是你所需要的

 options = $("#sel > option") options[Math.floor(Math.random() * options.length)].selected = true 

另外,使用class =“sel”而不是class =“。sel”

这将适用于您的HTML示例代码段。

 var options = $("#sel > option"); var random = Math.floor(options.length * (Math.random() % 1)); $("#sel > option").attr('selected',false).eq(random).attr('selected',true); 

将您的class级从“.sel”更改为“sel” ,然后尝试:

$(document).ready(function() { var index = Math.floor(Math.random() * $(".sel option").length) + 1; $("select option:nth-child(" + index + ")").prop("selected", true); });
$(document).ready(function() { var index = Math.floor(Math.random() * $(".sel option").length) + 1; $("select option:nth-child(" + index + ")").prop("selected", true); });