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

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

当前回答

// 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');

其他回答

// 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');

对我来说,只有当我添加下面这行代码时,它才能工作

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

如果您有禁用选项,您可以添加not([disabled])以防止选择它们,结果如下:

$("#target option:not([disabled]):first").attr('selected','selected')

虽然每个函数可能都不是必需的…

$('select').each(function(){
    $(this).find('option:first').prop('selected', 'selected');
});

对我有用。

在James Lee Baker的回复后面,我更喜欢这个解决方案,因为它消除了对浏览器支持的依赖:first:selected…

$('#target').children().prop('selected', false);
$($('#target').children()[0]).prop('selected', 'selected');