如何使用jquery从选择框中删除选项

Tom*_*Tom 5 jquery

如何使用jquery删除opt1行?如何将opt2更改为选中状态?请注意,值是随机数.

      <select name="ShippingMethod" >
        <option value="8247(random)">Opt2</option>
        <option value="1939(random)" selected="selected">Opt1</option>
      </select>
Run Code Online (Sandbox Code Playgroud)

Nic*_*ver 15

这取决于您要如何选择它,通过文本删除:

$("select[name=ShippingMethod] option").filter(function() { 
    return this.text == "Opt1"; 
}).remove();
Run Code Online (Sandbox Code Playgroud)

或者选择的一个:

$("select[name=ShippingMethod] option:selected").remove();
Run Code Online (Sandbox Code Playgroud)

或者第二个:

$("select[name=ShippingMethod] option:eq(1)").remove();
Run Code Online (Sandbox Code Playgroud)

或者最后一个:

$("select[name=ShippingMethod] option:last").remove();
Run Code Online (Sandbox Code Playgroud)

要只按文本选择选项2,您可以使用上述相同的.filter()方法:

$("select[name=ShippingMethod] option").filter(function() { 
    return this.text == "Opt2"; 
}).attr("selected", true);
Run Code Online (Sandbox Code Playgroud)

你可以在这里测试一下.