我有以下 JavaScript 方法
// METHOD 1
let categoryType = document.getElementById("create-listing-category-type");
let categoryTypeOption = categoryType.getElementsByTagName("option")[categoryType.selectedIndex].getAttribute("value");
// METHOD 2
let categoryType = document.getElementById("create-listing-category-type");
let categoryTypeOption = categoryType.options[categoryType.selectedIndex].value;
<div class="verification-main-input-div">
<p class="verification-main-text">Category</p>
<div class="drop-dawn-add-game-list">
<div class="arrow-drop-down-games-main">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-right chevron-for-drop-down"><polyline points="9 18 15 12 9 6"></polyline></svg>
</div>
<select id="create-listing-category-type" name="cars" class="drop-dawn-add-game-select">
<option value="Coins">Coins</option>
<option value="Items">Items</option>
<option value="Boosting">Boosting</option>
</select>
</div>
</div>
我想要完成的是从 <select>
获取所选选项的数据标签。当我只是 console.log(categoryTypeOption);
我得到默认值,即 Coins
,无论我是否选择另一个。我做错了什么?
这两种方法基于我在研究解决方案时找到的答案。
最佳答案
你的方法2有效...问题是你没有触发你的categoryTypeOption变量的重新计算。引用下面的代码片段...我向 select 标记添加了一个 onchange 事件处理程序。并将方法 2 代码移至处理函数中...
function onSelectChange() {
let categoryType = document.getElementById("create-listing-category-type");
let categoryTypeOption = categoryType.options[categoryType.selectedIndex].value;
console.log(categoryTypeOption);
}
<div class="verification-main-input-div">
<p class="verification-main-text">Category</p>
<div class="drop-dawn-add-game-list">
<div class="arrow-drop-down-games-main">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-chevron-right chevron-for-drop-down">
<polyline points="9 18 15 12 9 6"></polyline></svg>
</div>
<select id="create-listing-category-type" name="cars" class="drop-dawn-add-game-select" onchange="onSelectChange()">
<option value="Coins">Coins</option>
<option value="Items">Items</option>
<option value="Boosting">Boosting</option>
</select>
</div>
</div>
关于javascript - 使用 JavaScript 从选择标签获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62798126/