jQuery 通过通过变量传递的值选择选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11277117/
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
Selecting a select option by a value passed through a variable
提问by Ilyes Ferchiou
I have an html file that contains the following code :
我有一个包含以下代码的 html 文件:
<select id="gouv" name="gouv">
...some options here...
</select>
and the following jQuery code :
以及以下 jQuery 代码:
$('#gouv option[value="myvalue"]').attr("checked","checked");
this as you certainly know sets the option with the value "myvalue" to checked which works perfectly.
正如您肯定知道的那样,将值为“myvalue”的选项设置为已检查,这完美地工作。
Now the problem is, I don't know the value of the option I want to set as checked because this value is a result of some function which is stored within a global variable. For simplification sake, after long debugging, I reduced the problem to the following :
现在的问题是,我不知道要设置为选中的选项的值,因为该值是存储在全局变量中的某个函数的结果。为简单起见,经过长时间的调试,我将问题简化为以下内容:
var ident="myvalue";
$('#gouv option[value=ident]').attr("checked","checked");
and this code doesn't work !
并且此代码不起作用!
I would like to know why it doesn't work, can't we pass a value as a variable ? And is there any workaround to this ?
我想知道为什么它不起作用,我们不能将值作为变量传递吗?有什么解决方法吗?
回答by gdoron is supporting Monica
var ident="myvalue";
$('#gouv option[value="' + ident + '"]').attr("selected", "selected");
selected
is for <option>
, checked
is for radio!
selected
是为了<option>
,checked
是为了广播!
And better use prop
if your jQuery version is > 1.6
prop
如果您的 jQuery 版本 > 1.6,则更好地使用
$('#gouv option[value="' + ident +'"]').prop("selected", true);
Note that you better use filter
instead of attribute selector:
请注意,您最好使用filter
而不是属性选择器:
$('#gouv option').filter(function(){
return this.value == indent;
}).prop("selected", true);
Why you should use filter
for value
If you need to support blackberry, they have bug with option.value that jQuery handle:
如果你需要支持黑莓,他们有 jQuery 处理的 option.value 的错误:
$('#gouv option').filter(function(){
return $(this).val() == indent;
}).prop("selected", true);
回答by Mark Eirich
jQuery's .val()
(see here) will select an option by value:
jQuery .val()
(请参阅此处)将按值选择一个选项:
var ident = "myvalue";
$('#gouv').val(ident);
This is equivalent to:
这相当于:
var ident = "myvalue";
$('#gouv option[value="' + ident + '"]').attr("selected", "selected");
Except that the latter will have issues if ident
contains any double quotes.
除了后者如果ident
包含任何双引号会有问题。