如何从一个选择框中删除项目

如何从一个选择框中删除项目

在jQuery中,一个选项可以通过两种方法从选择框中移除。

方法1:直接删除框中的选项

要删除的选项是通过获得选择框选择的。要删除的值是在选择框的值选择器上指定的(value=’optionValue’)。然后使用remove()方法来删除这个被选中的选项。

语法:

$("selectBox option[value='optionValue']").remove()

示例:

<!DOCTYPE html>
<html>
<head>
    <title>
      Removing an item from a select box
  </title>
</head>
  
<body>
    <h1 style="color: green">
      GeeksForGeeks
  </h1>
    <b>Removing an item from a select box</b>
    <p>
        Select one from the given options:
        <select id="select1">
            <option value="free">
              Free
          </option>
            <option value="basic">
              Basic
          </option>
            <option value="premium">
              Premium
          </option>
        
    </p>
    <p>Click the button below to 
      remove one option from the select box.</p>
    <button onclick="removeOption()">
      Remove option
  
    <script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
  </script>
    
    <script type="text/javascript">
        function removeOption() {
  
            /* select the option with the 
            value of basic and remove the option*/
            $("#select1 option[value='basic']").remove();
        }
    </script>
</body>
  
</html>

输出:

  • 在点击按钮之前。
    如何从一个选择框中删除项目?
  • 点击该按钮后。
    如何从一个选择框中删除项目?

方法2:使用find()方法
find()方法可以用来寻找值选择器中的选项。这个方法在DOM中搜索指定元素的后代,并从匹配的元素中创建一个新的jQuery对象。

选择框首先被选中,然后应用find()方法与值选择器来寻找选项。然后使用remove()方法来删除这个被选中的选项。

语法:

$('selectBox').find('[value="basic"]').remove()

示例:

<!DOCTYPE html>
<html>
  
<head>
    <title>
      Removing an item from a select box
  </title>
</head>
  
<body>
    <h1 style="color: green">
      GeeksForGeeks
  </h1>
    <b>
      Removing an item from a select box
  </b>
    <p>
        Select one from the given options:
        <select id="select1">
            <option value="free">
              Free
          </option>
            <option value="basic">
              Basic
          </option>
            <option value="premium">
              Premium
          </option>
        
    </p>
    <p>
      Click the button below to remove 
      one option from the select box.
  </p>
    <button onclick="removeOption()">
      Remove option
  
    <script src=
"https://code.jquery.com/jquery-3.3.1.min.js">
  </script>
    <script type="text/javascript">
        function removeOption() {
  
            /* select the option with the 
            value of basic and remove the option*/
            $('#select1').find('[value="basic"]').remove();
        }
    </script>
</body>
  
</html>

输出:

  • 在点击按钮之前。
    如何从一个选择框中删除项目?
  • 点击该按钮后。
    如何从一个选择框中删除项目?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程