首页 > 解决方案 > 从 javascript (nightwatch.js) 的下拉菜单中选择随机值

问题描述

没有太多 javascript 或 nightwatch.js 经验,如果这似乎是显而易见的事情,我们深表歉意。

我有一个随机填充的下拉菜单。

我想做的是随机选择这些下拉菜单选项之一。

下拉菜单的html如下;

在此处输入图像描述

而且我想从列表中只选择一个条目(这当然会改变 - 包括条目和名称的数量 - 下次加载元素时)。

我有一个工作红宝石脚本;

modelrangeselect = @driver.find_element(:id, 'listRange_ddlItems')
carmodelrange = modelrangeselect.find_elements(:tag_name => 
'option').sample

但我就是不知道对应的javascript是什么,所以我可以在 nightwatch.js 上运行它。

任何帮助将非常感激。

谢谢。

标签: javascriptnightwatch.js

解决方案


在我看来,这应该足以随机选择其中一个选项,代码应该是不言自明的:)。

 // get the dropdown element
 const select  = document.getElementsByClassName('url-dropdown');

 // fetch all options within the dropdown
 const options = select.children;  

 // generate a random number between 0 and the total amount of options
 // the number will always be an index within the bounds of the array (options) 
 const random  = Math.floor(Math.random() * options.length);

 // set the value of the dropdown to a random option
 select.value = options[random].value; 

推荐阅读