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

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

当前回答

$("#target")[0].selectedIndex = 0;

其他回答

当你使用

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

如果第一个选项值为空,这将在Chrome和Safari中不起作用。

我更喜欢

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

因为它可以在所有浏览器中工作。

以下是我的做法:

$("#target option")
    .removeAttr('selected')
    .find(':first')     // You can also use .find('[value=MyVal]')
        .attr('selected','selected');

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

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

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

$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');