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

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

当前回答

就像这样简单:

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

其他回答

如果你要存储select元素的jQuery对象:

var jQuerySelectObject = $("...");

...

jQuerySelectObject.val(jQuerySelectObject.children().eq(0).val());
$("#target").val($("#target option:first").val());
// 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');

我发现,如果已经有一个选定的属性,只是设置attr选择不工作。我现在使用的代码将首先取消设置所选属性,然后选择第一个选项。

$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');
$("#target")[0].selectedIndex = 0;