如果想抓取 HTML 被選取中的那個 <option> 的內容,可以使用以下的方法:
- 取得
<select>元素。 - 取得
<select>元素的selectedIndex屬性,它會返回被選中的<option>的索引。 - 使用這個索引來抓取被選中的
<option>的內容。
我們這邊準備一個 html 如下:
<select id="mySelect">
<option value="1">選項一</option>
<option value="2">選項二</option>
<option value="3">選項三</option>
</select>
// 取得 select 元素
const selectElement = document.querySelector('#mySelect');
// 取得選取中的 option
const selectedOption = selectElement.options[selectElement.selectedIndex];
// 抓取選取中的 option 的內容
console.log(selectedOption.text);
給有需要的朋友參考。