通过jQuery随机选择选项

通过jQuery随机选择选项,jquery,forms,html-select,Jquery,Forms,Html Select,对于一个表单,我正在添加一个按钮,用于在单击时填充/选择一些随机数据(用于测试目的)。为此,我为输入元素创建了一些函数。对于选择列表,我希望执行以下操作: $form.find("select").each(function(){ let optionsCount = $(this).find('option').length; index = getRandomArbitrary(1,optionsCount-1); $(th

对于一个表单,我正在添加一个按钮,用于在单击时填充/选择一些随机数据(用于测试目的)。为此,我为输入元素创建了一些函数。对于选择列表,我希望执行以下操作:

$form.find("select").each(function(){
        let optionsCount = $(this).find('option').length;
        index = getRandomArbitrary(1,optionsCount-1);
        $(this+' :nth-child('+index+')').prop('selected', true); // $(this+' :nth-child('+index+')') is not valid
    });
这将随机选择列表中的一个选项——是的,上面的代码不起作用,但我不知道如何编写这样一个函数“通过jQuery随机选择选项”

我的意思是,主要的问题是我们不能将$(this)与伪值混合,我不知道如何扩展/更改选择器,使其远离$(this)


有人能给我一个提示吗?

正如您所发现的,您不能将
元素引用连接到jQuery对象中的选择器字符串。此问题的解决方案是使用
eq()
方法通过生成的随机索引查找每个
选择的子
选项。试试这个:

let$form=$('form');
$('.random')。在('单击',()=>{
$form.find(“select”)。每个((i,el)=>{
让$options=$(el.find('option');
让index=Math.floor(Math.random()*$options.length);
$options.eq(index.prop('selected',true));
});
});

随机选择
A.
B
C
D
E
F
G
A.
B
C
D
E
F
G
A.
B
C
D
E
F
G