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

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

当前回答

更改选择输入的值或调整所选属性会覆盖DOM元素的默认selectedOptions属性,导致元素在调用了重置事件的表单中可能无法正确重置。

使用jQuery的prop方法清除和设置所需的选项:

$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");

其他回答

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

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

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

$('#target').removeAttr('selected').find('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").prop("selectedIndex", 0);

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

.change ();

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

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