使用 jQuery 在选择列表中隐藏选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1271503/
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
Hide options in a select list using jQuery
提问by hitfactory
I have an object with key/value pairs of options I want to hide/remove from a select list. Neither of the following option selectors work. What am I missing?
我有一个带有键/值对选项的对象,我想从选择列表中隐藏/删除。以下选项选择器都不起作用。我错过了什么?
$.each(results['hide'], function(name, title) {
$("#edit-field-service-sub-cat-value option[value=title]").hide();
$("#edit-field-service-sub-cat-value option[@value=title]").hide();
});
回答by chaos
For what it's worth, the second form (with the @
) doesn't exist in jQuery 1.3. The first isn't working because you're apparently expecting variable interpolation. Try this:
无论如何,第二种形式(带有@
)在 jQuery 1.3 中不存在。第一个不起作用,因为您显然期待变量插值。尝试这个:
$("#edit-field-service-sub-cat-value option[value=" + title + "]").hide();
Note that this will probably break in various hideous ways if title
contains jQuery selector metacharacters.
请注意,如果title
包含 jQuery 选择器元字符,这可能会以各种可怕的方式中断。
回答by redsquare
You cannot do this x-browser. If I recall ie has issues. The easiest thing to do is keep a cloned copy of the select before you remove items, this allows you to easily remove and then append the missing items back.
你不能做这个 x 浏览器。如果我记得 ie 有问题。最简单的方法是在删除项目之前保留选择的克隆副本,这使您可以轻松删除然后附加丢失的项目。
回答by William Herry
I found a better way, and it is very simple:
我找到了一个更好的方法,而且很简单:
$("option_you_want_to_hide").wrap('<span/>')
To show again, just find that option(not span) and $("option_you_want_to_show").unwrap()
.
要再次显示,只需找到该选项(不是跨度)和$("option_you_want_to_show").unwrap()
.
It was tested on Chromeand Firefox.
它在Chrome和 Firefox上进行了测试。
回答by Caprica Six
Here is my spin, likely a bit faster due to native DOM methods
这是我的旋转,由于本机 DOM 方法,可能会快一点
$.each(results['hide'], function(name, title) {
$(document.getElementById('edit-field-service-sub-cat-value').options).each(function(index, option) {
if( option.value == title ) {
option.hidden = true; // not fully compatible. option.style.display = 'none'; would be an alternative or $(option).hide();
}
});
});
回答by enthusiastic123
This works in Firefox 3.0, but not in MSIE 8, nor in Opera 9.62:
这适用于 Firefox 3.0,但不适用于 MSIE 8,也不适用于 Opera 9.62:
jQuery('#destinations').children('option[value="1"]').hide();
jQuery('#destinations').children('option[value="1"]').css('display','none');
But rather hiding an option, one can simply disable it:
与其隐藏一个选项,不如简单地禁用它:
jQuery('#destinations').val('2');
jQuery('#destinations').children('option[value="1"]').attr('disabled','disabled');
The first of the the two lines above is for Firefox and pass focus to the 2nd option (assuming it has value="2"). If we omit it, the option is disabled, but the still displays the "enabled" option before we drop it down. Hence, we pass focus to another option to avoid this.
上面两行中的第一行用于 Firefox,并将焦点传递给第二个选项(假设它具有 value="2")。如果我们省略它,该选项将被禁用,但在我们将其下拉之前仍会显示“启用”选项。因此,我们将焦点传递给另一个选项以避免这种情况。
回答by Sablefoste
It CAN be done cross browser; it just takes some custom programming. Please see my fiddle at http://jsfiddle.net/sablefoste/YVMzt/6/. It was tested to work in Chrome, Firefox, Internet Explorer, and Safari.
可以跨浏览器完成;它只需要一些自定义编程。请在http://jsfiddle.net/sablefoste/YVMzt/6/查看我的小提琴。它经过测试可以在 Chrome、Firefox、Internet Explorer 和 Safari 中工作。
In short, I have a hidden field, #optionstore
, which stores the array sequentially (since you can't have Associative Arrays in JavaScript). Then when you change the category, it parses the existing options (first time through only) writes them to #optionstore
, erases everything, and puts back only the ones associated with the category.
简而言之,我有一个隐藏字段 ,#optionstore
它按顺序存储数组(因为在 JavaScript 中不能有关联数组)。然后,当您更改类别时,它会解析现有选项(仅第一次通过)将它们写入#optionstore
,擦除所有内容,并仅放回与类别关联的选项。
NOTE: I created this to allow different option values from the text displayed to the user, so it is highly flexible.
注意:我创建它是为了允许显示给用户的文本中有不同的选项值,因此它非常灵活。
The HTML:
HTML:
<p id="choosetype">
<div>
Food Category:
</div>
<select name="category" id="category" title="OPTIONAL - Choose a Category to Limit Food Types" size="1">
<option value="">All Food</option>
<option value="Food1">Fruit</option>
<option value="Food2">Veggies</option>
<option value="Food3">Meat</option>
<option value="Food4">Dairy</option>
<option value="Food5">Bread</option>
</select>
<div>
Food Selection
</div>
<select name="foodType" id="foodType" size="1">
<option value="Fruit1" class="sub-Food1">Apples</option>
<option value="Fruit2" class="sub-Food1">Pears</option>
<option value="Fruit3" class="sub-Food1">Bananas</option>
<option value="Fruit4" class="sub-Food1">Oranges</option>
<option value="Veg1" class="sub-Food2">Peas</option>
<option value="Veg2" class="sub-Food2">Carrots</option>
<option value="Veg3" class="sub-Food2">Broccoli</option>
<option value="Veg4" class="sub-Food2">Lettuce</option>
<option value="Meat1" class="sub-Food3">Steak</option>
<option value="Meat2" class="sub-Food3">Chicken</option>
<option value="Meat3" class="sub-Food3">Salmon</option>
<option value="Meat4" class="sub-Food3">Shrimp</option>
<option value="Meat5" class="sub-Food3">Tuna</option>
<option value="Meat6" class="sub-Food3">Pork</option>
<option value="Dairy1" class="sub-Food4">Milk</option>
<option value="Dairy2" class="sub-Food4">Cheese</option>
<option value="Dairy3" class="sub-Food4">Ice Cream</option>
<option value="Dairy4" class="sub-Food4">Yogurt</option>
<option value="Bread1" class="sub-Food5">White Bread</option>
<option value="Bread2" class="sub-Food5">Panini</option>
</select>
<span id="optionstore" style="display:none;"></span>
</p>
The JavaScript/jQuery:
JavaScript/jQuery:
$(document).ready(function() {
$('#category').on("change", function() {
var cattype = $(this).val();
optionswitch(cattype);
});
});
function optionswitch(myfilter) {
//Populate the optionstore if the first time through
if ($('#optionstore').text() == "") {
$('option[class^="sub-"]').each(function() {
var optvalue = $(this).val();
var optclass = $(this).prop('class');
var opttext = $(this).text();
optionlist = $('#optionstore').text() + "@%" + optvalue + "@%" + optclass + "@%" + opttext;
$('#optionstore').text(optionlist);
});
}
//Delete everything
$('option[class^="sub-"]').remove();
// Put the filtered stuff back
populateoption = rewriteoption(myfilter);
$('#foodType').html(populateoption);
}
function rewriteoption(myfilter) {
//Rewrite only the filtered stuff back into the option
var options = $('#optionstore').text().split('@%');
var resultgood = false;
var myfilterclass = "sub-" + myfilter;
var optionlisting = "";
myfilterclass = (myfilter != "")?myfilterclass:"all";
//First variable is always the value, second is always the class, third is always the text
for (var i = 3; i < options.length; i = i + 3) {
if (options[i - 1] == myfilterclass || myfilterclass == "all") {
optionlisting = optionlisting + '<option value="' + options[i - 2] + '" class="' + options[i - 1] + '">' + options[i] + '</option>';
resultgood = true;
}
}
if (resultgood) {
return optionlisting;
}
}
回答by eoleary
Your best bet is to set disabled=true on the option items you want to disable, then in CSS set
最好的办法是在要禁用的选项项上设置 disabled=true,然后在 CSS set
option:disabled {
display: none;
}
That way even if the browser doesn't support hiding the disabled item, it still can't be selected.. but on browsers that dosupport it, they will be hidden.
这样,即使浏览器不支持隐藏禁用的项目,但它仍然无法选择。但对浏览器不支持的话,他们将被隐藏。
回答by MadTurki
In reference to redsquare's suggestion, I ended up doing this:
参考 redsquare 的建议,我最终这样做了:
var selectItems = $("#edit-field-service-sub-cat-value option[value=" + title + "]").detach();
and then to reverse this:
然后扭转这个:
$("#edit-field-service-sub-cat-value").append(selectItems);
回答by Russ Cam
Take a look at this question and the answers -
看看这个问题和答案 -
Looking at your code, you may need to quote the attribute value
查看您的代码,您可能需要引用属性值
$("#edit-field-service-sub-cat-value option[value='title']").hide();
from jQuery attribute selectors
Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]"
在大多数情况下,引号是可选的,但是当值包含诸如“]”之类的字符时,应该使用引号来避免冲突
EDIT:
编辑:
Just realised that you're getting the title from the function parameter, in which case the syntax should be
刚刚意识到您从函数参数中获取标题,在这种情况下,语法应该是
$("#edit-field-service-sub-cat-value option[value='" + title + "']").hide();
回答by Oranit Dar
The problem is that Internet Explorer does not seem to support the hide and show methods for select options. I wanted to hide all options of my ddlReasonCode select which did not have the currently selected type as the value of the attribute "attType".
问题是 Internet Explorer 似乎不支持选择选项的隐藏和显示方法。我想隐藏我的 ddlReasonCode select 的所有选项,这些选项没有将当前选择的类型作为属性“attType”的值。
While the lovely Chrome was quite satisfied with:
而可爱的 Chrome 则相当满意:
//Hiding all options
$("#ddlReasonCode").children().hide();
//Showing only the relevant options
$("#ddlReasonCode").children("option[atttype=\"" + CurrentType + "\"]").show();
This is what IE required (kids, don't try this at CHROME :-)):
这是 IE 所要求的(孩子们,不要在 CHROME 上尝试这个 :-)):
//Hiding all options
$("#ddlReasonCode option").each(function (index, val) {
if ($(this).is('option') && (!$(this).parent().is('span')) && ($(this).atttype != CurrentType))
$(this).wrap('<span>').hide();
});
//Showing only the relevant options
$("#ddlReasonCode option").each(function (index, val) {
if (this.nodeName.toUpperCase() === 'OPTION') {
var span = $(this).parent();
var opt = this;
if ($(this).parent().is('span') && ((this).atttype == CurrentType)) {
$(opt).show();
$(span).replaceWith(opt);
}
}
});
I found that wrapping idea at http://ajax911.com/hide-options-selecbox-jquery/