我如何使第一个选项的选择与jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
我如何使第一个选项的选择与jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
当前回答
当你使用
$("#target").val($("#target option:first").val());
如果第一个选项值为空,这将在Chrome和Safari中不起作用。
我更喜欢
$("#target option:first").attr('selected','selected');
因为它可以在所有浏览器中工作。
其他回答
就像这样简单:
$('#target option:first').prop('selected', true);
var firstItem = $(“感兴趣类型”)。(“selectedIndex”道具,0)。瓦尔();
控制台日志(firstItem)。
对我来说,只有当我添加下面这行代码时,它才能工作
$('#target').val($('#target').find("option:first").val());
$("#target")[0].selectedIndex = 0;
当你使用
$("#target").val($("#target option:first").val());
如果第一个选项值为空,这将在Chrome和Safari中不起作用。
我更喜欢
$("#target option:first").attr('selected','selected');
因为它可以在所有浏览器中工作。