javascript隐藏/显示下拉列表中的项目
我开始学习JavaScript语言,想知道是否有人知道如何在html的下拉列表中隐藏值?
I started studying javascripting and was wondering if anyone know how to hide values in dropdown list for html?
例如:具有值的dropwwon列表
For example: a dropdwon list with values
Select One
Item1
Item2
Item3
Item4
Item5
我想这样隐藏项目4和5,并在单击显示..."时显示它.
I wanna hide the Item 4 and 5, like this and show it when "Show... " is clicked.
Select One
Item1
Item2
Item3
Show 2 more items (Item 4 and 5 hidden)
有可能吗?下面是我已经开始的一段代码.
Is that possible? Below is a piece of code i already started.
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
选项和带有类的隐藏项.
You want a generic solution, so tag the more
option and the hidden items with classes.
事实证明,您无法在所有浏览器中始终一致地在select
中对option
进行样式设置,因此您需要动态更改列表选项:请参阅以下问题:
It turns out you cannot consistently style-out option
s in a select
across browsers, so you need to dynamically alter the list options: Refer to this question: How to hide a <option> in a <select> menu with CSS?
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
选项并显示隐藏的元素:
Previous info:
Then on then select
change event you hide the more
option and show the hidden elements:
$('select').change(function(){
var $select = $(this);
if ($select.val() == "More"){
$('.more').hide().prevAll('.hidden').show();
}
});
在select
中似乎存在一个奇怪的错误,因为最后一个项目始终可见(即使已样式化!).我现在添加了一个空白条目来解决此问题.这也是为什么我没有将隐藏项放置在最后一个项之后的情况,因为最后一个项总是显示(这是一个奇怪的错误-作为一个新问题提出来:为什么总是显示上次选择选项,即使已设置样式也是如此).
There appears to be a weird bug in select
s as the last item is always visible (even when styled out!). I added a blank entry to fix this for now. This is also why I did not place the hidden items after the more as the last one always shows (what a strange bug - have asked that as a new question: Why is last select option always shown, even when styled out).
您还将希望清除所选的更多"值,因为该值将不再存在.
You will also want to clear the selected value of "More" as that will no longer exist.
$('select').change(function () {
var $select = $(this);
if ($select.val() == "More") {
$('.more').hide().prevAll('.hidden').show();
$select.val('');
}
});
跟进:
Followup:
Based on my related question, I was pointed to this one: How to hide a <option> in a <select> menu with CSS? Apparently you cannot style out select options consistently, so adding the items to the list dynamically would be the ideal solution.