代码之家  ›  专栏  ›  技术社区  ›  Tom

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

  •  5
  • Tom  · 技术社区  · 15 年前

    如何使用jquery删除opt1行?把opt2改成selected怎么样? 请注意,这些值是随机数。

          <select name="ShippingMethod" >
            <option value="8247(random)">Opt2</option>
            <option value="1939(random)" selected="selected">Opt1</option>
          </select>
    
    2 回复  |  直到 15 年前
        1
  •  14
  •   Nick Craver    15 年前

    这取决于你想如何选择它, to remove by text :

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

    Or the selected one :

    $("select[name=ShippingMethod] option:selected").remove();
    

    Or the second one :

    $("select[name=ShippingMethod] option:eq(1)").remove();
    

    Or the last one :

    $("select[name=ShippingMethod] option:last").remove();
    

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

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

    You can test it here .

        2
  •  0
  •   El Yobo    15 年前

    关于问题二的快速猜测

    $('select[name=ShippingMethod]').val('19395ss');
    

    尼克·卡弗似乎回答了第一个问题。