【问题标题】:How to remove options when clicked on a button单击按钮时如何删除选项
【发布时间】:2021-11-11 13:46:03
【问题描述】:

如何在单击嵌套在选择元素内的按钮时删除选项?

是我在 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>

【问题讨论】:

  • 我建议你从Javascript中输入颜色,然后去除颜色,或者添加颜色,会更容易实现。
  • 嗯,我在做作业,我的教授在 html 中给出了它,所以我无法更改它
  • 这能回答你的问题吗? Remove values from select list based on condition
  • 我之前查过,没试过

标签: javascript html


【解决方案1】:

只需使用 .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>

【讨论】:

    【解决方案2】:

    链接的问题将解决您的问题,稍作改动。

    这里的值是使用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>

    【讨论】:

    • 这里的值被删除oninput事件,你必须弄清楚使用按钮点击,这是你的功课。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多