2011-06-08 120 views
4

我想在jQuery手機的選擇菜單中設置默認選擇。該文檔有這樣的:在JQuery Mobile的選擇菜單中設置默認選擇?

var myselect = $("select#foo"); 
    myselect[0].selectedIndex = 3; 
    myselect.selectmenu("refresh"); 

其中我加入正下方,我創建菜單,但後來當我運行的代碼,我得到這個錯誤:

throw "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'";

不知道該怎麼在這一點上做的...

+0

問題是你操縱的對象還不存在。我提供的修改示例(將代碼綁定到包含頁面的頁面)是否可以解決您的錯誤? – ironchefpython 2011-06-17 13:10:48

回答

7

你試圖操縱DOM與尚未加載JavaScript對象。將javascript移動到您嘗試操作的窗體之上,或者將更多代碼移至在文檔加載時執行的函數中。

例如:

$('#PAGE').live('pagecreate',function(event){ 
    var myselect = $("select#foo"); 
    myselect[0].selectedIndex = 3; 
    myselect.selectmenu("refresh"); 
}); 

其中PAGE是你加載該頁面的id包含你要操作的菜單。


編輯:

我更新使用基於有關JQuery Mobile events錦園的評論的jQuery Mobile的pagecreate事件的例子。

+1

document.ready不適用於jqm。 使用.live()綁定事件,如'pageshow,pagehide' 檢查事件列表的演示。 http://jquerymobile.com/test/#/test/docs/api/events.html – root 2011-06-17 04:07:01

+0

@jinyuan感謝您的澄清 – ironchefpython 2011-06-17 04:13:37

+0

與標記有關的JS的位置告訴你很少,幾乎沒有什麼關於什麼時候這些是「活「 – 2012-09-18 11:34:31

2

在jQuery功能:

$.fn.jqmSelectedIndex = function(index){ 
    var self = $(this) 
    self 
     .prop('selectedIndex', index) 
    .selectmenu("refresh"); 

    return self; 
} 

$("select#foo").jqmSelectedIndex(3); 

這不是有效的,但作品。