如何使用 JavaScript 隐藏选择选项?(跨浏览器)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4398966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I hide select options with JavaScript? (Cross browser)
提问by dave1010
This should work:
这应该有效:
$('option').hide(); // hide options
It works in Firefox, but not Chrome (and probably not in IE, not tested).
它适用于 Firefox,但不适用于 Chrome(可能不适用于 IE,未经测试)。
A more interesting example:
一个更有趣的例子:
<select>
<option class="hide">Hide me</option>
<option>visible option</option>
</select>
<script type="text/javascript">
// try to hide the first option
$('option.hide').hide();
// to select the first visible option
$('option:visible').first().attr('selected', 'selected');
</script>
Or see the example at http://jsfiddle.net/TGxUf/
或查看http://jsfiddle.net/TGxUf/ 上的示例
Is the only option to detach the option elements from the DOM? I need to show them again later, so this would not be very effective.
是从 DOM 中分离选项元素的唯一选择吗?我需要稍后再向他们展示,所以这不会很有效。
回答by alex
Unfortunately, you can't hide option
elements in all browsers.
不幸的是,您无法option
在所有浏览器中隐藏元素。
In the past when I have needed to do this, I have set their disabled
attribute, like so...
过去当我需要这样做时,我已经设置了它们的disabled
属性,就像这样......
$('option').prop('disabled', true);
I've then used the hiding where it is supported in browsers using this piece of CSS...
然后,我使用这段 CSS 在浏览器支持的地方使用了隐藏...
select option[disabled] {
display: none;
}
回答by Blazemonger
As has been said, you can't display:none
individual <option>
s, because they're not the right kind of DOM elements.
如前所述,您不能display:none
单独使用<option>
s,因为它们不是正确的 DOM 元素。
You can set .prop('disabled', true)
, but this only grays out the elements and makes them unselectable -- they still take up space.
您可以设置.prop('disabled', true)
,但这只会使元素变灰并使它们无法选择——它们仍然占用空间。
One solution I use is to .detach()
the <select>
into a global variable on page load, then add back only the <option>
s you want on demand. Something like this (http://jsfiddle.net/mblase75/Afe2E/):
一种解决方案我的用途是.detach()
在<select>
进入页面加载一个全局变量,然后添加回的只有<option>
你想按需秒。像这样(http://jsfiddle.net/mblase75/Afe2E/):
var $sel = $('#sel option').detach(); // global variable
$('a').on('click', function (e) {
e.preventDefault();
var c = 'name-of-class-to-show';
$('#sel').empty().append( $sel.filter('.'+c) );
});
At first I thought you'd have to .clone()
the <option>
s before appending them, but apparently not. The original global $sel
is unaltered after the click
code is run.
起初我还以为你不得不.clone()
在<option>
小号追加在他们面前,但显然不是。代码运行$sel
后原全局不变click
。
If you have an aversion to global variables, you could store the jQuery object containing the options as a .data()
variable on the <select>
element itself (http://jsfiddle.net/mblase75/nh5eW/):
如果您不喜欢全局变量,则可以将包含选项的 jQuery 对象存储为元素本身的.data()
变量<select>
(http://jsfiddle.net/mblase75/nh5eW/):
$('#sel').data('options', $('#sel option').detach()); // data variable
$('a').on('click', function (e) {
e.preventDefault();
var $sel = $('#sel').data('options'), // jQuery object
c = 'name-of-class-to-show';
$('#sel').empty().append( $sel.filter('.'+c) );
});
回答by dave1010
Had a crack at it myself and this is what I came up with:
我自己对此有所了解,这就是我想出的:
(function($){
$.fn.extend({detachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
s.find(o).each(function() {
d.push($(this).detach());
});
s.data('selectOptions', d);
});
}, attachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
for (var i in d) {
if (d[i].is(o)) {
s.append(d[i]);
console.log(d[i]);
// TODO: remove option from data array
}
}
});
}});
})(jQuery);
// example
$('select').detachOptions('.removeme');
$('.b').attachOptions('[value=1]');');
You can see the example at http://www.jsfiddle.net/g5YKh/
您可以在http://www.jsfiddle.net/g5YKh/查看示例
The option
elements are fully removed from the select
s and can be re-added again by jQuery selector.
的option
元件被从完全除去select
S和可再加入由jQuery选择一次。
Probably needs a bit of work and testing before it works well enough for all cases, but it's good enough for what I need.
在它适用于所有情况之前可能需要一些工作和测试,但它足以满足我的需要。
回答by Matt T. McAlear
I know this is a little late but better late than never! Here's a really simple way to achieve this. Simply have a show and hide function. The hide function will just append every option element to a predetermined (hidden) span tag (which should work for all browsers) and then the show function will just move that option element back into your select tag. ;)
我知道这有点晚了,但迟到总比没有好!这是实现这一目标的非常简单的方法。只需具有显示和隐藏功能。hide 函数只会将每个选项元素附加到一个预先确定的(隐藏的)span 标签(它应该适用于所有浏览器),然后 show 函数只会将该选项元素移回您的选择标签。;)
function showOption(value){
$('#optionHolder option[value="'+value+'"]').appendTo('#selectID');
}
function hideOption(value){
$('select option[value="'+value+'"]').appendTo('#optionHolder');
}
回答by jAndy
Hiding an <option>
element is not in the spec. But you can disable
them, which should work cross-browser.
隐藏<option>
元素不在规范中。但是您可以使用disable
它们,这应该可以跨浏览器工作。
$('option.hide').prop('disabled', true);
回答by NeverEndingLearner
You can try wrapping the option elements inside a spanso that they wont be visible but still be loaded in the DOM. Like below
您可以尝试将 option 元素包装在 span 中,这样它们就不会可见,但仍会加载到 DOM 中。像下面
jQ('#ddlDropdown option').wrap('<span>');
And unwrap the option which contains the 'selected' attribute as follows to display already selected option.
并按如下方式解开包含 'selected' 属性的选项以显示已选择的选项。
var selectedOption = jQ('#ddlDropdown').find("[selected]");
jQ(selectedOption).unwrap();
This works across all the browsers.
这适用于所有浏览器。
回答by Wim Barelds
Here's an option that:
这是一个选项:
- Works in all browsers
- Preserves current selection when filtering
- Preserves order of items when removing / restoring
- No dirty hacks / invalid HTML
- 适用于所有浏览器
- 过滤时保留当前选择
- 删除/恢复时保留项目的顺序
- 没有肮脏的黑客/无效的 HTML
`
`
$('select').each(function(){
var $select = $(this);
$select.data('options', $select.find('option'));
});
function filter($select, search) {
var $prev = null;
var $options = $select.data('options');
search = search.trim().toLowerCase();
$options.each(function(){
var $option = $(this);
var optionText = $option.text();
if(search == "" || optionText.indexOf(search) >= 0) {
if ($option.parent().length) {
$prev = $option;
return;
}
if (!$prev) $select.prepend($option);
else $prev.after($option);
$prev = $option;
}
else {
$option.remove();
}
});
}
`
`
JSFiddle: https://jsfiddle.net/derrh5tr/
JSFiddle:https://jsfiddle.net/derrh5tr/
回答by SpoonNZ
Three years late, but my Googling brought me here so hopefully my answer will be useful for someone else.
晚了三年,但我的谷歌搜索把我带到了这里,所以希望我的回答对其他人有用。
I just created a second option (which I hid with CSS) and used Javascript to move the s backwards and forwards between them.
我刚刚创建了第二个选项(我用 CSS 隐藏了它)并使用 Javascript 在它们之间来回移动 s。
<select multiple id="sel1">
<option class="set1">Blah</option>
</select>
<select multiple id="sel2" style="display:none">
<option class="set2">Bleh</option>
</select>
Something like that, and then something like this will move an item onto the list (i.e., make it visible). Obviously adapt the code as needed for your purpose.
类似的东西,然后类似的东西会将一个项目移动到列表中(即,使其可见)。显然,根据您的目的需要调整代码。
$('#sel2 .set2').appendTo($('#sel1'))
回答by Fatih Alp
It's possible if you keep in object and filter it in short way.
如果您保持对象并以短方式对其进行过滤,则有可能。
<select id="driver_id">
<option val="1" class="team_opion option_21">demo</option>
<option val="2" class="team_opion option_21">xyz</option>
<option val="3" class="team_opion option_31">ab</option>
</select>
-
——
team_id= 31;
var element = $("#driver_id");
originalElement = element.clone(); // keep original element, make it global
element.find('option').remove();
originalElement.find(".option_"+team_id).each(function() { // change find with your needs
element.append($(this)["0"].outerHTML); // append found options
});
回答by xam
This is an enhanced version of @NeverEndingLearner's answer:
这是@NeverEndingLearner 答案的增强版:
- full browsers support for not using unsupported CSS
- reserve positions
- no multiple wrappings
- 完整的浏览器支持不使用不受支持的 CSS
- 储备职位
- 没有多重包装
$("#hide").click(function(){
$("select>option.hide").wrap('<span>'); //no multiple wrappings
});
$("#show").click(function(){
$("select span option").unwrap(); //unwrap only wrapped
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<select>
<option class="hide">Hide me</option>
<option>visible option</option>
</select>
<button id="hide">hide</button>
<button id="show">show</button>