Javascript 设置 dijit.form.Select 小部件的值(选定选项)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2215979/
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
Setting the value (selected option) of a dijit.form.Select widget
提问by aehlke
I have a dijit.form.Select widget. It's tied to a data store, if that matters. It's filled with several options already. All I want to do is programmatically set its value. I can get its value using myWidget.attr('value')but if I try to do myWidget.attr('value', 5)for example (where 5 is one of the valid values), all it does is reset the widget to select the very first option, no matter what value I give it.
我有一个 dijit.form.Select 小部件。如果这很重要,它与数据存储相关联。它已经充满了几个选项。我想要做的就是以编程方式设置它的值。我可以使用它来获取它的值,myWidget.attr('value')但是如果我尝试这样做myWidget.attr('value', 5)(其中 5 是有效值之一),它所做的只是重置小部件以选择第一个选项,无论我给它什么值。
This seems to be a bug, and there aren't any tests or documentation which show how to accomplish what I want to. But is there some way, even if it's a dirty hack?
这似乎是一个错误,并且没有任何测试或文档显示如何完成我想要的操作。但是有没有办法,即使它是一个肮脏的黑客?
I'm using Dojo 1.4.0. Note that dijit.form.Select is the new name for dojox.form.DropDownSelect.
我正在使用 Dojo 1.4.0。请注意,dijit.form.Select 是 dojox.form.DropDownSelect 的新名称。
edit: I even tried resetting the widget with all new options, but it ignores the option which has selected = trueand just selects the first option. There must still be a way though.
编辑:我什至尝试使用所有新选项重置小部件,但它忽略了具有selected = true并只选择第一个选项的选项。不过应该还是有办法的。
回答by voidstate
Even if your values are ints, if you set your integer to a string then this will work.
即使您的值是整数,如果您将整数设置为字符串,那么这将起作用。
dijit.byId( 'my_select' ).attr( 'value', String( 5 ) );
回答by aehlke
Turns out it's a bug - if the option values aren't strings, it won't work (mine were integers).
原来这是一个错误 - 如果选项值不是字符串,它将不起作用(我的是整数)。
回答by jbarz
Repost of my comment: There is a test page here: dojo archivethat you can mess with. Using fire-bug I used dijit.byId('s9').attr('value', 'CO') successfully on that page. That will set the "store-based" Select on that page.
重新发布我的评论:这里有一个测试页面:您可以使用的dojo 存档。使用 fire-bug 我在该页面上成功使用了 dijit.byId('s9').attr('value', 'CO') 。这将在该页面上设置“基于商店的”选择。
But as you said I set it using a string and you were using integers so I didn't see the bug. Good catch.
但是正如您所说,我使用字符串设置它,而您使用的是整数,所以我没有看到错误。接得好。

