我如何使第一个选项的选择与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>
当前回答
虽然每个函数可能都不是必需的…
$('select').each(function(){
$(this).find('option:first').prop('selected', 'selected');
});
对我有用。
其他回答
如果你要存储select元素的jQuery对象:
var jQuerySelectObject = $("...");
...
jQuerySelectObject.val(jQuerySelectObject.children().eq(0).val());
它只适用于我在最后使用触发器('change'),就像这样:
$("#target option:first").attr('selected','selected').trigger('change');
当你使用
$("#target").val($("#target option:first").val());
如果第一个选项值为空,这将在Chrome和Safari中不起作用。
我更喜欢
$("#target option:first").attr('selected','selected');
因为它可以在所有浏览器中工作。
对我来说,只有当我添加下面这行代码时,它才能工作
$('#target').val($('#target').find("option:first").val());
另一种重置值(对于多个选定元素)的方法是:
$("selector").each(function(){
/*Perform any check and validation if needed for each item */
/*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */
this.selectedIndex=0;
});