jQuery 确定 html select 是否在其任何子选项中包含值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3149072/
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
Determine if html select contains a value in any of its child options
提问by Dan
Given a select
给定一个选择
<select id="Myselect">
<option value="-1">Please Select<option>
<option value="1">Selection 1<option>
<option value="2">Selection 2<option>
</select>
What the best way to determine if there is an option of value X in the select with JQuery?
用 JQuery 确定在选择中是否有值 X 的选项的最佳方法是什么?
回答by Nick Craver
You can do this using a selector and .length
, like this:
您可以使用选择器和来执行此操作.length
,如下所示:
var exists = $("#mySelect option[value='-1']").length !== 0;
Or as a function:
或者作为一个函数:
function optionExists(val) {
return $("#mySelect option[value='" + val + "']").length !== 0;
}
If it's not numbers and you may have '
in there for example (screwing the selector), you can use .filter()
, like this:
如果它不是数字,并且您可能'
在其中(例如拧紧选择器),则可以使用.filter()
,如下所示:
function optionExists(val) {
return $("#mySelect option").filter(function() {
return this.value === val;
}).length !== 0;
}
回答by naspinski
The :has()selector should work, something like this:
的:有()选择应该工作,是这样的:
var exists = $("#Myselect:has(option[value='X'])").length > 0;
This is far from the only way, but an easy to understand approach.
You could also do somethi.g like this for an .Exists()function since .length > 0
is sometimes not clear to mean it does exist.
这远不是唯一的方法,而是一种易于理解的方法。你也可以为 .Exists()函数做一些这样的事情,因为.length > 0
有时不清楚它确实存在。