javascript 如何使用jquery更改选择框中呈现的选定选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6222559/
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
How to change rendered selected option in select box with jquery
提问by user472749
I have tried many ways to select an option with jquery including .val("0")
.attr('selected', 'selected')
and .attr('selected', 'true')
and the TexoTela plugin. They all seem to update the html but the browser still shows the last item selected by the user.
我尝试了很多方法来使用 jquery 选择一个选项,包括.val("0")
.attr('selected', 'selected')
和.attr('selected', 'true')
和TexoTela 插件。它们似乎都更新了 html,但浏览器仍然显示用户选择的最后一个项目。
Try out this fiddle... Select the dropdown value 1 and then click the link.
试试这个小提琴...选择下拉值 1,然后单击链接。
Is there any way to actually update the displayed value?
有没有办法实际更新显示的值?
回答by WSkid
You mean change which item is selected?
您的意思是更改选择的项目?
$('select').val('0');
$('select').val('0');
There are other ways, but this is the basic, following your example.
还有其他方法,但这是基本的,遵循您的示例。
You can read up on the documenation for .val()
here, and the snippet:
您可以阅读.val()
此处的文档和片段:
checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
检查或选择所有单选按钮、复选框和选择与值集匹配的选项。
EDIT for jQuery Mobile
编辑 jQuery Mobile
For jQuery Mobile you also need to refresh the select as mentioned in the mobile docs:
对于 jQuery Mobile,您还需要刷新移动文档中提到的选择:
If you manipulate a select via JavaScript, you must call the refresh method on it to update the visual styling.
如果您通过 JavaScript 操作选择,则必须对其调用 refresh 方法以更新视觉样式。
You can do this by:
您可以通过以下方式执行此操作:
$('select').selectmenu("refresh",true);
$('select').selectmenu("refresh",true);
回答by mikey
You're setting the option value to zero.
您将选项值设置为零。
Set the select not the option val
设置选择而不是选项 val
$('select').val('0');
and you'll probably want to use an #id instead just a 'select' selector.
并且您可能希望使用 #id 而不是“选择”选择器。
回答by Lehme
Still use your .val("0")
to set the value, and to update in the browser you have to use one of the following:
仍然使用您.val("0")
的设置值,并在浏览器中更新您必须使用以下之一:
.trigger("liszt:updated");
or
或者
.trigger("chosen:updated");
Just one will work, depending on how you create your select.
只需要一个就行,这取决于您创建选择的方式。
It's gonna be like:
它会是这样的:
$("#Your_select").val('0');
$("#Your_select").trigger("liszt:updated");