我如何使第一个选项的选择与jQuery?

<select id="target">
  <option value="1">...</option>
  <option value="2">...</option>
</select>

当前回答

它只适用于我在最后使用触发器('change'),就像这样:

$("#target option:first").attr('selected','selected').trigger('change');

其他回答

// remove "selected" from any options that might already be selected
$('#target option[selected="selected"]').each(
    function() {
        $(this).removeAttr('selected');
    }
);


// mark the first option as selected
$("#target option:first").attr('selected','selected');

我认为,关于投票最多的答案,我发现了一个微妙的问题:即使它们正确地更改了所选的值,它们也不会更新用户看到的元素(只有当用户单击小部件时,才会在更新的元素旁边看到一个复选框)。

将.change()调用链接到末尾也会更新UI小部件。

$("#target").val($("#target option:first").val()).change();

(注意,我是在使用jQuery Mobile和Chrome桌面框时注意到这一点的,所以这可能不是到处都是情况)。

另一种重置值(对于多个选定元素)的方法是:

$("selector").each(function(){

    /*Perform any check and validation if needed for each item */

    /*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */

    this.selectedIndex=0;

});

就像这样简单:

$('#target option:first').prop('selected', true);

对我来说,它只在我添加以下代码时起作用:

.change ();

对我来说,它只在我添加以下代码时起作用: 因为我想要“重置”表单,也就是说,选择表单的所有选择的所有第一个选项,我使用了以下代码:

$(“形式”);(“选择”). each(函数(){ (美元)。瓦尔($(“选择选项:第一”).val ()); (美元).change (); });