如何在單擊嵌套在 select 元素中的按鈕時洗掉選項?
我的錯誤是在 for 回圈中嗎?我想不通
var select = document.getElementById('colorSelect');
var options = document.getElementsByTagName('option');
console.log(options);
function removecolor() {
for (var i = 0; i < options.length; i ) {
console.log(select.value);
//Here i need to delete option value that is selected
}
}
<form>
<select id="colorSelect">
<option>Red</option>
<option>Green</option>
<option>White</option>
<option>Black</option>
</select>
<input type="button" onclick="removecolor()" value="Select and Remove"><br>
</form>
uj5u.com熱心網友回復:
只需使用 .remove
const select = document.getElementById('colorSelect');
document.getElementById("remove").addEventListener("click",function() {
const opt = select.options[select.selectedIndex];
if (opt) opt.remove()
})
<form>
<select id="colorSelect">
<option>Red</option>
<option>Green</option>
<option>White</option>
<option>Black</option>
</select>
<input type="button" id="remove" value="Select and Remove"><br>
</form>
如果不允許更改 HTML 和事件處理程式,則可以執行
const select = document.getElementById('colorSelect');
function removecolor() {
const opt = select.options[select.selectedIndex];
if (opt) opt.remove()
}
<form>
<select id="colorSelect">
<option>Red</option>
<option>Green</option>
<option>White</option>
<option>Black</option>
</select>
<input type="button" onclick="removecolor()" value="Select and Remove"><br>
</form>
uj5u.com熱心網友回復:
鏈接的問題將解決您的問題,略有變化。
這里使用oninput事件洗掉值
var selectobject = document.getElementById("colorSelect");
function func() {
console.log(selectobject.value)
selectobject.options[selectobject.selectedIndex].remove();
}
<select id="colorSelect" oninput="func()">
<option>Red</option>
<option>Green</option>
<option>White</option>
<option>Black</option>
</select>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/355986.html
標籤:javascript html
