利用CSS和Javascript選擇下拉式選單中的選項
P粉739706089
P粉739706089 2023-09-04 22:10:59
0
1
528
<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>
P粉739706089
P粉739706089

全部回覆(1)
P粉665427988

您的HTML結構對我來說似乎有問題。一個input元素不包含optionsselect元素才包含。我的程式碼片段向您展示如何以程式設計方式將select下拉式選單的值指派給第二個選項,即APPLE。

它也使用了您現有的結構(根據您的查詢派生),但是最後一個元素不再使用input,而是使用select,因為從語義上講,inputoptions不符合邏輯。所以,如果我的解釋有誤,我的解決方案可能無法準確回答您的問題。但是我希望它仍然可以引導您朝著正確的方向發展。

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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!