利用CSS和Javascript选择下拉菜单中的选项
<p>我有一个CSS选择器值:</p>
<pre class="brush:php;toolbar:false;">.ng-touched > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > input:nth-child(1)</pre>
<p>我正在尝试使用document.querySelectorAll来查找这个CSS选择器,它有一个下拉菜单,<strong>并选择文本为“APPLE”的选项</strong>。它是下拉菜单中的第二个选项。
为此,我正在使用以下代码,但运行代码后,选项“APPLE”没有被选中:</p>
<pre class="brush:php;toolbar:false;">document.querySelectorAll(".ng-touched > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > input:nth-child(1)")
.forEach(o => {
o.value = "APPLE";
});</pre>
<p>请指导我出了什么问题,以及应该对代码进行哪些必要的更改。提前谢谢。</p>
您的HTML结构对我来说似乎有问题。一个
input元素不包含options;select元素才包含。我的代码片段向您展示了如何以编程方式将select下拉菜单的值分配给第二个选项,即APPLE。它还使用了您现有的结构(根据您的查询派生),但是最后一个元素不再使用
input,而是使用select,因为从语义上讲,input与options不符合逻辑。所以,如果我的解释有误,我的解决方案可能无法准确回答您的问题。但是我希望它仍然可以指导您朝正确的方向发展。const select = document.querySelector(".ng-touched > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > select:nth-child(1)") // setTimeout used to visualize how GOOGLE changes to APPLE. setTimeout(() => { // You can access the options of the select with .options. // Then you can programatically set the selected value by index. select.options.selectedIndex = 1 }, 2000)<div class="ng-touched"> <div style="padding-left: 16px;"> <div style="padding-left: 16px;"> <div> </div> <div style="padding-left: 16px;"> <select id="companies"> <option value="google">GOOGLE</option> <option value="apple">APPLE</option> <option value="facebook">FACEBOOK</option> <option value="amazon">AMAZON</option> </select> </div> </div> </div> </div>