我开始学习 javascripting,想知道是否有人知道如何在 html 的下拉列表中隐藏值?
例如:一个带有值的下拉列表
Select One
Item1
Item2
Item3
Item4
Item5
我想像这样隐藏第 4 项和第 5 项,并在单击“显示...”时显示它。
Select One
Item1
Item2
Item3
Show 2 more items (Item 4 and 5 hidden)
这可能吗?下面是一段我已经开始的代码。
var css = select;
var markers = cluster.getMarkers();
var markersLength = markers.length;
var nextOption = new Option("Select One");
css.add(nextOption, 0);
for(var i = 0; i < markersLength; i++) {
nextOption = new Option(markers[i].title);
try {
css.add(nextOption, -1);
} catch (e) {
css.add(nextOption, null);
}
}
最佳答案
你想要一个通用的解决方案,所以标记 more
选项和带有类的隐藏项。
事实证明,您无法跨浏览器在 select
中一致地设置 option
的样式,因此您需要动态更改列表选项:请参阅此问题:How to hide a <option> in a <select> menu with CSS?
最终解决方案(从另一个隐藏的 select
追加元素):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/93D3h/12/
HTML:
Select One
<select class="hidden">
<option>Item4</option>
<option>Item5</option>
<option>Item6</option>
<option>Item7</option>
<select>
<select>
<option>Item1</option>
<option>Item2</option>
<option>Item3</option>
<option class="more">More</option>
</select>
jQuery:
$('select').change(function(){
var $select = $(this);
if ($select.val() == "More"){
$('.more').remove();
$select.append($('.hidden').children());
}
});
以前的信息:
然后在 select
更改事件中隐藏 more
选项并显示隐藏的元素:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/93D3h/2/
$('select').change(function(){
var $select = $(this);
if ($select.val() == "More"){
$('.more').hide().prevAll('.hidden').show();
}
});
在 select
中似乎有一个奇怪的错误,因为最后一项总是可见的(即使在设计时也是如此!)。我添加了一个空白条目来暂时解决这个问题。 这也是为什么我没有将隐藏的项目放在最后一个总是显示的更多之后(多么奇怪的错误 - 作为一个新问题提出:Why is last select option always shown, even when styled out ).
您还需要清除所选的“更多”值,因为该值将不再存在。
例如http://jsfiddle.net/TrueBlueAussie/93D3h/3/
$('select').change(function () {
var $select = $(this);
if ($select.val() == "More") {
$('.more').hide().prevAll('.hidden').show();
$select.val('');
}
});
跟进:
根据我的相关问题,我被指向了这个问题:How to hide a <option> in a <select> menu with CSS? 显然你不能一致地设置选择选项的样式,因此将项目动态添加到列表将是理想的解决方案。
关于javascript 隐藏/显示下拉列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25115392/