Javascript 通过选择列表中的文本而不是通过索引进行选择
我是JavaScript新手 我知道如何通过Javascript 通过选择列表中的文本而不是通过索引进行选择,javascript,Javascript,我是JavaScript新手 我知道如何通过 document.getElementById("entry_1000001").selectedIndex=2 但是有没有什么方法可以直接通过文本进行选择 document.getElementById("entry_1000001").select("Ruby") HTML元素如下 <select name="entry.1000001" id="entry_1000001" aria-label="What language does
document.getElementById("entry_1000001").selectedIndex=2
但是有没有什么方法可以直接通过文本进行选择
document.getElementById("entry_1000001").select("Ruby")
HTML元素如下
<select name="entry.1000001" id="entry_1000001" aria-label="What language does Watir-WebDriver use? " aria-required="true" required=""><option value=""></option>
<option value="Java">Java</option> <option value="Ruby">Ruby</option> <option value="C#">C#</option> <option value="Clojure">Clojure</option> <option value="Python">Python</option></select>
Java Ruby C#Clojure Python
document.getElementById(“条目_1000001”).value=“Ruby”代码>
JAVA
红宝石
C#
Clojure
python
当然,document.getElementById(“entry_1000001”).value=“Ruby”代码>我以为这个值方法是用于文本字段的,我不知道选择列表也有这个值方法,谢谢。@RAJ是的,(如果该选项存在),它会在引擎盖下将其设置为选中的。您可以稍后通过执行var sel=document.getElementById(“entry_1000001”)轻松测试上述内容;日志(选择选项[selectedIndex])好的,谢谢。我还有一个问题,如果我没有该字段的id,我可以使用名称字段定位吗,我只找到getElementsByName方法。当我没有任何id且有名称时,有什么方法可以定位元素吗?@RAJ有几种方法document.getElementsByName(“foo”)[0]
其中0
是元素的索引,或者通过循环检索到的集合来定位元素。更新的、稍微慢一点的(根本不重要)版本是document.querySelector(“[name='foo']”)
非常棒,谢谢!我现在开始学习JavaScript,以便嵌入到我的自动化脚本中。非常感谢。