代码之家  ›  专栏  ›  技术社区  ›  Cheok Yan Cheng

如何使用JQuery选择nth选项

  •  29
  • Cheok Yan Cheng  · 技术社区  · 15 年前

    我有下面的HTML

    <select onchange="this.form.submit()" name="name">
        <option value="9995101E01#17201044055PM">9995101E01#17201044055PM</option>
        <option value="GRR-Example">GRR-Example</option>
        <option value="admin">admin</option>
        <option value="123w">123w</option>
    </select>
    

    我可以知道如何使用JQuery选择值“admin”吗?

    6 回复  |  直到 8 年前
        1
  •  88
  •   Darin Dimitrov    15 年前
    $('select[name=name] option:eq(2)').attr('selected', 'selected');
    

    Demo .

        2
  •  11
  •   Alex    15 年前

    这样地:

    $("select[name='name'] option:eq(2)").attr("selected", "selected");
    

    编辑:

    要在新编辑中执行所需的操作,即选择值为的选项 admin :

    $("select[name='name'] option:contains('admin')").attr("selected", "selected");
    

    See it working .

        3
  •  7
  •   Greg    9 年前

    我认为 nth-child 你要找的是伪类:

    $('select option:nth-child(3)').attr('selected', 'selected');
    
        4
  •  4
  •   Denis Matafonov    9 年前

    我不建议使用 .attr('selected', 'selected') . 这是不好的做法。如果两个选项具有“select”属性,那么select的值是多少?

    以下是简单易行的版本:

     $('select[name="name"]').val('admin');
    

    DEMO

        5
  •  2
  •   Community Mohan Dere    8 年前

    只是更新一下,以防有人需要帮助。我有一个类似的要求,但在我的例子中,下拉列表存储为一个JavaScript变量。我也喜欢 Denis Matafonov 建议选择有问题的选项。下面是最后一段代码:

    var target_dd = $('select[name=name]');
    $(target_dd).val($(target_dd).find('option:eq(2)').html());
    
        6
  •  0
  •   Tomasz Mularczyk    9 年前

    如果要选择第n个选项 触发onchange事件,然后:

    function selectOption(nr) {
        var select = $("select");
        if (select.children().length >= nr) {
            let value = select.find('option:eq(' + nr + ')').val();
            select.val(value).change();
        }
    }