javascript jQuery - 选定的选项值包含字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18250555/
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
jQuery - selected option value contains string
提问by Tom
I have an if statement where I'm trying to set a variable if the selected value of a select element does not contain "ALL"
我有一个 if 语句,如果 select 元素的选定值不包含“ALL”,我将尝试设置一个变量
Here's the code I've tried, but it always returns "%"...
这是我试过的代码,但它总是返回“%”...
if(!$("select.mySelect option:selected").filter(":contains('ALL')")) {
selected_option = $("select.mySelect option:selected");
} else {
selected_option = "%";
}
HTML
HTML
<select class="mySelect">
<option value="ALLTYPE1">All type 1</option>
<option value="CAR">Car</option>
<option value="VAN">Van</option>
<option value="ALLTYPE2">All type 2</option>
<option value="PLANE">Plane</option>
<option value="HELICOPTER">Helicopter</option>
</select>
Any ideas?
有任何想法吗?
采纳答案by techfoobar
Your if
statement is incorrect. .filter()
will never returna false value - it'll always be a jQuery collection - which can be empty, but never false. To test it there are any elements in the jQuery collection returned by .filter()
, use the .length
property.
你的if
说法是不正确的。.filter()
永远不会返回假值——它永远是一个 jQuery 集合——它可以是空的,但永远不会是假的。要测试它返回的 jQuery 集合中有任何元素.filter()
,请使用该.length
属性。
Use:
利用:
if($("select.mySelect option:selected").filter(":contains('ALL')").length === 0) {
...