[英]How to remove options when clicked on a button
如何在单击嵌套在 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>
只需使用 .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>
链接的问题将解决您的问题,略有变化。
这里使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.