javascript - 从 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 上运行它。
任何帮助将非常感激。
谢谢。
解决方案
在我看来,这应该足以随机选择其中一个选项,代码应该是不言自明的:)。
// 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;
推荐阅读
- javascript - Highcharts - 如何从 java 地图中设置 x 轴和 y 轴的数据
- python-3.x - 无法从 Fargate 容器中访问 S3 存储桶(错误请求并且无法找到凭据)
- haskell - How should I structure constrained parameters in Haskell?
- regex - Vim 如何使用正则表达式删除一些单词
- python - python matplotlib中指定间隔的绘图函数
- javascript - 处理具有许多变量的操作的更好方法?
- php - 选择性地将 PHP 输出记录到日志文件,而不是将其打印到浏览器
- visual-studio-2017 - VS2017 安装失败;无法通过安装程序或 Microsoft 开发社区报告
- amazon-s3 - 在 Terraform 中将多个 AWS 账户作为环境处理的最佳方式是什么?
- sql-server - NodeJs Connection Error querying SQL Server