2012-04-25 111 views
1

我一直想弄清楚,但仍然卡住了。 所以我使用PhoneGap for iOS和JQueryMobile。 我試圖顯示單擊按鈕時的警報。jquery mobile + phonegap onclick

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" /> 
<!-- If your application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here --> 
<script type="text/javascript" charset="utf-8" src="cordova-1.6.1.js"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> 
     </script> 
    <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"> 
     </script> 

,我有這個

<a href="#" id="button" data-role="button" data-theme="b"> Login </a> $(document).ready("#button").click(function() { alert('button clicked'); });

當我試圖在Chrome推出這個,這個工作正常。然而,當我使用iphone模擬器時,它不顯示任何東西。

回答

7

對於你在一個JQM應用程序中使用DOM已準備就緒即

$(function(){ // <-- this is a shortcut for $(document).ready(function(){ ... }); 
    $('#button').click(function(){ 
     alert('button clicked'); 
    }); 
}); 

但是一個正常的Web應用程序是有用得多綁定到「pageinit」,即

$(document).on('pageinit','[data-role=page]',function(){ 
    $('#button').click(function(){ 
     alert('button clicked'); 
    }); 
}); 

結合pageinit作品更好,因爲JQM將新頁面插入與第一頁相同的dom。正因爲如此,你準備好的所有代碼都不會再被調用。所以,我上面提到的第一部分代碼只適用於JQM應用程序的第一頁。無論您的按鈕位於哪個頁面,第二個都可以工作。請讓我知道我是否可以爲您進一步澄清此問題。

+0

謝謝,我想這個問題實際上是最新的PhoneGap版本。然後我使用PhoneGap 1.5,它工作正常。 – ordinaryman09 2012-04-26 01:18:26

+0

我還有一個問題,如果你不介意。 所以我有這個index.html和login.html,我使用href鏈接從索引到登錄。 並在每個index.html和login.html中導入javascript。 但是,似乎只有那些來自正在加載的index.html。 因此,如果我將index.html中的js放在login.html中,它可以正常工作。 但是,我們將它分開放置(另一個js用於login.html,它不在index.html中),但它不起作用。 – ordinaryman09 2012-04-26 01:19:41

+1

我認爲這是最好的問題,而不是在評論中 – Todd 2012-04-26 01:53:30