javascript 在 JQuery Mobile 的选择菜单中设置默认选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6286620/
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 a default selection in a select menu in JQuery Mobile?
提问by tweetypi
I'm trying to set the default selection in a select menu in JQuery mobile. The docs have this:
我正在尝试在 JQuery mobile 的选择菜单中设置默认选择。文档有这个:
var myselect = $("select#foo");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
Which I added right underneath where I create the menu, but then when I run the code I get this error:
我在创建菜单的正下方添加了它,但是当我运行代码时,我收到此错误:
throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'";
抛出“无法在初始化之前调用“+名称+”上的方法;“+”尝试调用方法“”+选项+“”;
Not sure what to do at this point...
不知道此时该怎么办...
回答by ironchefpython
You're trying to manipulate DOM objects with javascript that haven't loaded yet. Move the javascript past the form you're trying to manipulate, or more your code into a function that executes on document load.
您正在尝试使用尚未加载的 javascript 操作 DOM 对象。将 javascript 移过您尝试操作的表单,或者将更多代码移到在文档加载时执行的函数中。
For example:
例如:
$('#PAGE').live('pagecreate',function(event){
var myselect = $("select#foo");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
});
where PAGE
is the id of the page you're loading that contains the menu you want to manipulate.
PAGE
您正在加载的包含您要操作的菜单的页面的 id在哪里。
EDIT:
编辑:
I updated the example to use the JQuery Mobile pagecreate event based on jinyuan's comment regarding JQuery Mobile events.
我根据 jinyuan 对JQuery Mobile events的评论更新了示例以使用 JQuery Mobile pagecreate事件。
回答by Renzo Castro
As jQuery function:
作为 jQuery 函数:
$.fn.jqmSelectedIndex = function(index){
var self = $(this)
self
.prop('selectedIndex', index)
.selectmenu("refresh");
return self;
}
$("select#foo").jqmSelectedIndex(3);
This isn't validated but works.
这未经验证但有效。
回答by root
it works. maybe you might want to provide more details.
有用。也许您可能想提供更多详细信息。