jquery 选择选项不起作用(按名称)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10182200/
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 select option not working (by name)
提问by Michelle Dupuis
I have the following HTML which defines my selector:
我有以下 HTML 定义了我的选择器:
<select name="zoom_cat[]" style="margin-left:15px;">
<option value="-1" selected="selected">All</option>
<option value="0">News</option>
<option value="1">Publications</option>
<option value="2">Services</option>
<option value="3">Industries</option>
</select>
And I am trying to set the selected option to All (value -1). For some reason this jquery code is having no effect (same option remains selected):
我正在尝试将所选选项设置为全部(值 -1)。出于某种原因,这个 jquery 代码没有效果(相同的选项仍然被选中):
$('input[name="zoom_cat[]"] option[value="-1"]').attr('selected', 'selected');
回答by Matt Mombrea
$('select[name="zoom_cat[]"] option[value="-1"]').attr('selected', 'selected');
instead of input
代替 input
回答by Shyju
Use select
instead of input
使用select
代替input
$('select[name="zoom_cat[]"] option[value="-1"]').attr('selected', 'selected');
working sample : http://jsfiddle.net/Est9D/4/
工作示例:http: //jsfiddle.net/Est9D/4/
You can do it in more simple way
你可以用更简单的方式来做
$('select[name="zoom_cat[]"]').val("-1")
Sample : http://jsfiddle.net/Est9D/7/
回答by Geekfish
As Matt above said, you should use select
in your selector, not input
, they are different elements. Also setting the selected attribute will not work on <=IE7, so ideally you should do $('select[name="zoom_cat[]"]').val('-1');
正如马特上面所说,您应该select
在选择器中使用,而不是input
,它们是不同的元素。同样设置 selected 属性在 <=IE7 上不起作用,所以理想情况下你应该这样做$('select[name="zoom_cat[]"]').val('-1');
回答by Andrew Thomson
You need to escape special characters in your selector.
您需要在选择器中转义特殊字符。
See: http://api.jquery.com/category/selectors/
请参阅:http: //api.jquery.com/category/selectors/
So try this instead:
所以试试这个:
$('input[name="zoom_cat\\[\\]"] option[value="-1"]').attr('selected', 'selected');
$('input[name="zoom_cat\\[\\]"] option[value="-1"]').attr('selected', 'selected');
回答by michael
You can do this: (not attr as suggested by someone but prop)
你可以这样做:(不是有人建议的 attr 而是 prop)
$('select[name="zoom_cat[]"] option[value="-1"]').prop('selected', 'selected');
$('select[name="zoom_cat[]"] option[value="-1"]').prop('selected', 'selected');