使用 JavaScript 删除下拉列表中的选定值

Lar*_*mus 2 html javascript jquery drop-down-menu

我有一个 HTML 列表,我想根据用户的选择从中删除元素。我尝试使用此线程中的代码,但我的问题似乎是访问该元素。这是我的 HTML:

<div id="ShipPlacement">
Ship:
<select name="shipSelec" id="shipSelec">
    <option value="aircraftCarrier">Aircraft Carrier</option>
    <option value="battleship">Battleship</option>
    <option value="cruiser">Cruiser</option>
    <option value="destroyer">Destroyer</option>
    <option value="destroyer">Destroyer</option>
    <option value="submarine">Submarine</option>
    <option value="submarine">Submarine</option>
</select>
<button type="button" onclick="placeShip()">Remove Selected Ship</button>
Run Code Online (Sandbox Code Playgroud)

这是我的 JavaScript:

$( document ).ready(function() {
   var shipList=document.getElementById('shipSelec');
});
function placeShip() {
  shipList.remove(shipList.options[shipList.selectedIndex].value;);
  shipList.remove(shipList.options[shipList.selectedIndex]);
  shipList.remove(shipList.options[selectedIndex]);
  shiplist.remove([shipList.selectedIndex])
}
Run Code Online (Sandbox Code Playgroud)

我有几个该remove()方法的实例,但没有一个起作用。但是,我向您传达错误的最佳方式是通过 JSFiddle。

Tus*_*har 5

当您在页面上加载 jQuery 时,使用它来绑定事件并从 DOM 中删除元素。

首先,使用 绑定按钮上的单击事件click。使用:selected伪选择器从下拉列表中选择所选选项并将remove()其从 DOM 中删除。

$('button').click(function() {
    $('#shipSelec option:selected').remove();
});
Run Code Online (Sandbox Code Playgroud)

$('button').click(function() {
    $('#shipSelec option:selected').remove();
});
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function() {
  $('button').click(function() {
    $('#shipSelec option:selected').remove();
  });
});
Run Code Online (Sandbox Code Playgroud)

更新了小提琴


请注意,您的代码中有几个问题

  1. 在小提琴中,“LOAD TYPE”选项应选择“No Wrap”。
  2. 不包括 jQuery。可以使用 JavaScript 选项卡中的“框架和扩展”选项包含此内容
  3. placeShip()附近第一个语句中有语法错误.value;);
  4. shipList是回调本地的ready,因此无法从外部访问。甚至不在placeShip()

使用纯 JavaScript

var shipList = document.getElementById('shipSelec');
shipList.options[shipList.selectedIndex].remove();
Run Code Online (Sandbox Code Playgroud)

小提琴