jQuery如何选择第一个非隐藏的选择选项 [英] jQuery how to select the first non-hidden select option
问题描述
以下行为在jQuery 1.9和1.10 +之间有所不同:
< select id =s1>
< option value =1> 1< / option>
< option value =2> 2< / option>
< option value =3> 3< / option>
< / select>
$('#s1 option [value = 1]')。hide();
$('#s1')。val('');
此代码背后的想法是在隐藏某些选项后选择第一个非隐藏选项,包括因为jQuery 1.10+ $('#s1')。val('');
不再选择第一个非隐藏选项,而 .val(<对于特定选择框>的某个适当值)
可以正常工作。
尝试以下方法并无帮助,因为 selectedIndex
和 .first()。val()
考虑隐藏的选项:
$(#s1)。prop(selectedIndex,0);
$ b $ p $('#s1 option')。first()。prop('selected',true); $ b
下一个想到的事情(也由 C-link )也不起作用,因为:visible
选择器对于选择选项无法正常工作。
$('#s1 option:visible')。fir st()。prop('selected',true);
寻找一些通用的方法(不依赖于什么是特定的值和隐藏的选项)来实现与旧的jQuery中的 $('#s1')。val('');
相同的行为。 b $ b
从其他人的答案/评论编译如下:
$('#s1 option')。each(function(){
if($(this).css('display')!='none'){
$(this ).prop(selected,true);
返回false;
}
});
The following behaves differently between jQuery 1.9 and 1.10+:
<select id="s1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
$('#s1 option[value=1]').hide();
$('#s1').val('');
The idea behind this code is to select the first non-hidden option, after hiding some options, including the currently selected one.
Since jQuery 1.10+ the $('#s1').val('');
no longer selects the first non-hidden option, while .val(<some proper value for the particular select box>)
works ok.
Trying the following approaches does not help because both selectedIndex
and .first().val()
consider the hidden options:
$("#s1").prop("selectedIndex", 0);
$('#s1 option').first().prop('selected', true);
Next thing that comes to mind (also suggested by C-link) also does not work, because the :visible
selector does not work properly for select options.
$('#s1 option:visible').first().prop('selected', true);
Looking for some generic way (not depending on knowledge of what are the particular values and what options have been hidden) to achieve the same behaviour as $('#s1').val('');
in old jQuery.
Compiled from everybody else's answers/comments the following:
$('#s1 option').each(function () {
if ($(this).css('display') != 'none') {
$(this).prop("selected", true);
return false;
}
});
这篇关于jQuery如何选择第一个非隐藏的选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!