如果我有一个如下所示的下拉列表:
<select id="mySelect">
<option>Apple</option>
<option>Pineapple</option>
<option>Lime</option>
<option>Pear</option>
<option>Orange</option>
</select>
我可以以某种方式使用索引号来显示下拉列表中的前三个选项吗?
$("#mySelect").find("OPTION").each(function(index) {
console.log(index + ": " + $(this).text());
});
获取以下输出,但我只想让下拉列表显示0,1和2.没有可能修改列表本身并删除2个选项。
0: Apple
1: Pineapple
2: Lime
3: Pear
4: Orange
答案 0 :(得分:0)
您可以简单地hide()
您不想显示的选项。
您可以使用选择器option
:nth-of-type(n+4)
$('#mySelect option:nth-of-type(n+4)').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
<option>Apple</option>
<option>Pineapple</option>
<option>Lime</option>
<option>Pear</option>
<option>Orange</option>
</select>
答案 1 :(得分:0)
使用
$('#mySelect option').eq(2).nextAll('option').remove();
这将删除3个选项后的所有选项
$('#mySelect option').eq(2).nextAll('option').remove();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
<option>Apple</option>
<option>Pineapple</option>
<option>Lime</option>
<option>Pear</option>
<option>Orange</option>
</select>
&#13;
答案 2 :(得分:0)
$("#mySelect").find("OPTION").each(function(index) {
console.log(index + ": " + $(this).text());
if(index > 2){
$(this).hide();
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
<option>Apple</option>
<option>Pineapple</option>
<option>Lime</option>
<option>Pear</option>
<option>Orange</option>
</select>
&#13;
答案 3 :(得分:0)
隐藏索引2以外的任何内容
$(function(){
$( ".parent .thumbnail" ).each(function( index, element ) {
$('<div class="child childofParent1">Child Inserted'+(index+1)+'</div>').insertBefore(element);
});
});
$('#mySelect option:gt(2)').hide();
答案 4 :(得分:0)
尝试以下js也可以,
$(document).ready(function() {
$("#mySelect").children('option:gt(2)').hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
<option>Apple</option>
<option>Pineapple</option>
<option>Lime</option>
<option>Pear</option>
<option>Orange</option>
</select>