使用 JQuery 隐藏选择的选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4699410/
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
Hiding Options of a Select with JQuery
提问by Syed Abdul Rahman
Okay, let's start with an example.
Keep in mind, this is only an example.
好的,让我们从一个例子开始。
请记住,这只是一个示例。
<select id = "selection1">
<option value = "1" id = "1">Number 1</option>
<option value = "2" id = "2">Number 2</option>
<option value = "3" id = "3">Number 3</option>
</select>
<select id = "selection1">
<option value = "1" id = "1">Number 1</option>
<option value = "2" id = "2">Number 2</option>
<option value = "3" id = "3">Number 3</option>
</select>
Now from here, we have a dropdown with 3 options.
What I want to do now is to hide an option.
现在从这里开始,我们有一个包含 3 个选项的下拉列表。
我现在想做的是隐藏一个选项。
Adding style = "display:none"
will nothelp.
The option would not appear in the dropdownlist, but using the arrow keys, you can still select it.
Essentially, it does exactly what the code says. It isn't displayed, and it stops there.
添加style = "display:none"
将不会帮助。
该选项不会出现在下拉列表中,但您仍然可以使用箭头键选择它。
本质上,它完全按照代码所说的去做。它没有显示,它停在那里。
A JQuery function of $("#1").hide()
will not work.
Plus, I don't only want to hide the option, I want to completely remove it.
的 JQuery 函数$("#1").hide()
将不起作用。
另外,我不仅想隐藏该选项,还想完全删除它。
Any possibility on doing so?
Do I have to use parent/sibling/child elements? If so, I'm still not sure how.
这样做有没有可能?
我必须使用父/兄弟/子元素吗?如果是这样,我仍然不确定如何。
Any help on this would be greatly appreciated. Thanks.
对此的任何帮助将不胜感激。谢谢。
Another question - It's related
另一个问题 - 这是相关的
Ok, so I found out that there is a .remove()
available in JQuery. Works well.
But what if I want to bring it back?
好的,所以我发现.remove()
JQuery中有一个可用的。效果很好。
但是如果我想把它带回来怎么办?
if(condition)
{
$(this).remove();
}
if(condition)
{
$(this).remove();
}
I can loops this. Shouldn't be complicated.
But the thing of which I am trying to do is this:
我可以循环这个。应该不复杂。
但我想做的事情是这样的:
Maximum Capacity of Class: (Input field here)
Select Room: (Dropdown here)
班级的最大容量:(在此处输入字段)
选择房间:(在此处下拉)
What I'd like for it to do is to update is Dropdown using a function such as .change()
or .keyup
.
I could create the dropdown only after something is typed. At a change or a keyup, execute the dropdown accordingly.
But what I am doing is this:
我想要它做的是使用诸如.change()
or 之类的函数来更新 Dropdown .keyup
。
只有在输入内容后,我才能创建下拉列表。在更改或 keyup 时,相应地执行下拉菜单。
但我正在做的是:
$roomarray = mysql_query("SELECT *
FROM
(
SELECT *,
CASE
WHEN type = 'Classroom' THEN 1
WHEN type = 'Computer laboratory' THEN 2
WHEN type = 'Lecture Hall' THEN 3
WHEN type = 'Auditorium' THEN 4
END AS ClassTypeValue
FROM rooms
) t
ORDER BY ClassTypeValue, maxppl, roomID");
$roomarray = mysql_query("SELECT *
FROM
(
SELECT *,
CASE
WHEN type = 'Classroom' THEN 1
WHEN type = 'Computer Laboratory' THEN 2
WHEN type = '演讲厅' THEN 3
WHEN type = 'Auditorium' THEN 4
END AS ClassTypeValue
FROM rooms
) t
ORDER BY ClassTypeValue, maxppl, roomID");
echo "<select id = \"room\">";
while ($rooms = mysql_fetch_array($roomarray))
{ ?>
<option value=<?php echo $rooms['roomID']; ?> id=<?php echo $rooms['roomID']; ?>><?php echo $rooms['type']; echo " "; echo $rooms['roomID']; echo " ("; echo $rooms['maxppl']; echo ")"; ?></option>
<?php
}
echo "</select>";
Yes, I know it is very messy.
I plan to change it later on.
是的,我知道它很乱。
我打算以后再改。
But the issue now is this: Can I toggle the removal of the options according to what has been typed?
Is it possible to do so with a dropdown made from a loop? Because I sure as hell can't keep executing SQL Queries. Or is that even an option? Because if it's possible, I still think it's a bad one.
但现在的问题是:我可以根据输入的内容切换选项的删除吗?
是否可以通过循环制作的下拉菜单来做到这一点?因为我绝对不能继续执行 SQL 查询。或者这甚至是一种选择?因为如果可能的话,我仍然认为这是一个坏的。
回答by Kees C. Bakker
The hide() doesn't work for Chrome... I've been experimenting with a work-around and wrapped it in a plugin I called "ExtraBox". The idea is to store the options temporary so we can enable / disable them by manipulating the DOM. I've created the plugin to make it easier to use.
hide() 不适用于 Chrome...我一直在尝试一种变通方法并将其包装在一个我称为“ExtraBox”的插件中。这个想法是临时存储选项,以便我们可以通过操作 DOM 来启用/禁用它们。我创建了插件以使其更易于使用。
I've posted the code on jsFiddle, so you can try it for yourself: http://jsfiddle.net/KeesCBakker/HaFRC/. [note: first project in jsFiddle, I'm loving it!]
我已经在 jsFiddle 上发布了代码,所以你可以自己尝试一下:http: //jsfiddle.net/KeesCBakker/HaFRC/。[注意:jsFiddle 中的第一个项目,我很喜欢它!]
Html example:
html示例:
Select:
<br/>
<select id="TestKees">
<option value="1" class="s1">First value</option>
<option value="2" class="s2">Second value</option>
<option value="3" class="s3">Third value</option>
</select>
<br/>
Enable / Disable
<br/>
<input id="txt" type="text" value="s2" />
<button id="btnEnable">Enable</button>
I've added the following jQuery to my document.ready function:
我已将以下 jQuery 添加到我的 document.ready 函数中:
$('#TestKees').extraBox({ attribute: 'class' });
$('#btnEnable').click(function(){
$('#TestKees').data('extraBox').enable(
$('#txt').val()
);
});
$('#btnDisable').click(function(){
$('#TestKees').data('extraBox').disable(
$('#txt').val()
);
});
The plugin looks like this:
该插件如下所示:
(function($) {
// Create ExtraBox object
function ExtraBox(el, options) {
// Default options for the plugin (configurable)
this.defaults = {
attribute: 'class'
};
// Combine default and options objects
this.opts = $.extend({}, this.defaults, options);
// Non-configurable variables
this.$el = $(el);
this.items = new Array();
};
// Separate functionality from object creation
ExtraBox.prototype = {
init: function() {
var _this = this;
$('option', this.$el).each(function(i, obj) {
var $el = $(obj);
$el.data('status', 'enabled');
_this.items.push({
attribute: $el.attr(_this.opts.attribute),
$el: $el
});
});
},
disable: function(key){
$.each(this.items, function(i, item){
if(item.attribute == key){
item.$el.remove();
item.$el.data('status', 'disabled');
}
});
},
enable: function(key){
var _this = this;
$.each(this.items, function(i, item){
if(item.attribute == key){
var t = i + 1;
while(true)
{
if(t < _this.items.length) {
if(_this.items[t].$el.data('status') == 'enabled') {
_this.items[t].$el.before(item.$el);
item.$el.data('status', 'enabled');
break;
}
else {
t++;
}
}
else { _this.$el.append(item.$el);
item.$el.data('status', 'enabled');
break;
}
}
}
});
}
};
// The actual plugin - make sure to test
// that the element actually exists.
$.fn.extraBox = function(options) {
if (this.length) {
this.each(function() {
var rev = new ExtraBox(this, options);
rev.init();
$(this).data('extraBox', rev);
});
}
};
})(jQuery);
回答by fearofawhackplanet
Why are you messing around with display settings if you just want to remove the element?
如果您只想删除元素,为什么还要搞乱显示设置?
$('#1').remove();
and its gone.
它消失了。
回答by Glen Little
I've made available a jQuery Plugin that solves this very nicely. With it, you would do this:
我提供了一个 jQuery 插件,可以很好地解决这个问题。有了它,你会这样做:
$('#selection1').hideOption('1');
$('#selection1').showOption('1');
You can hide and show them as much as you want, and they will keep their original order. It works in all browsers. You can see that in this sample: jsFiddle - Toggle Dropdown Options
您可以根据需要隐藏和显示它们,它们将保持原始顺序。它适用于所有浏览器。您可以在此示例中看到:jsFiddle - Toggle Dropdown Options
You can get the Toggle Dropdown Options plug-in. If you don't like plug-ins, just copy the JavaScript code from it to your own project's JavaScript file. See the Read the Docslink on the plug-in for more information!
您可以获得Toggle Dropdown Options 插件。如果您不喜欢插件,只需将其中的 JavaScript 代码复制到您自己项目的 JavaScript 文件中即可。有关更多信息,请参阅插件上的阅读文档链接!
回答by jAndy
As far as I know, this is not possible natively. You can
disable
an<option>
node tho. To completlely hide/remove it you would need to write some custom code.$('option').attr('disable', true);
By the way, you shouldn't use a single number as an ID for an element. Use somekind of prefix, i.e.
option_1
.
据我所知,这在本地是不可能的。你可以
disable
一个<option>
节点。要完全隐藏/删除它,您需要编写一些自定义代码。$('option').attr('disable', true);
顺便说一下,您不应该使用单个数字作为元素的 ID。使用某种前缀,即
option_1
.
it actually is possible to hide an <option>
node, but not cross-browser compatible.
实际上可以隐藏<option>
节点,但不能跨浏览器兼容。
回答by shybovycha
I suppose, your selector is wrong. Try something like this (updated):
我想,你的选择器是错误的。尝试这样的事情(更新):
<html>
<head>
<title>MooExample</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#click").click(function() {
$("#selection1 #1").remove();
//$("#selection1 > #1").toggle(); // Hide OR show
});
});
</script>
</head>
<body>
<select id="selection1">
<option value="1" id="1">Number 1</option>
<option value="2" id="2">Number 2</option>
<option value="3" id="3">Number 3</option>
</select>
<input type="button" id="click" onclick="moo()" value="click" />
</body>
</html>
See parent-child selector(parent > child).
请参阅父子选择器(父 > 子)。
回答by Manoj Thapliyal
This Is Very Simple In Jquery
这在 Jquery 中非常简单
//For Hide
$('#selection1 option[value=1]').hide();
//For Show
$('#selection1 option[value=1]').show();