2012-05-01 5 views
4

特定の時間間隔に基づいてページを変更しようとしています。 私はsetTimeoutを使ってみましたが、指定された時間に関係なくすぐにコードを実行します。 ページは次のとおりです。setTimeoutがJQuery Mobileで指定された間隔を待機していない

<!DOCTYPE HTML> 
<html> 
    <head> 
     <meta name="viewport" content="width=320; user-scalable=no" /> 
     <meta http-equiv="Content-type" content="text/html; charset=utf-8"> 
     <title>Change Page</title> 
     <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" /> 
     <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> 
     <script type="text/javascript"> 
      var oCSS = { 
       'font-size' : '18em', 
       'height' : '300px', 
       'border' : 'thick solid', 
       'text-align' : 'center' 
      }; 

      $(document).bind("mobileinit", function() 
      { 
       $.mobile.defaultPageTransition = "flip"; 
      }); 
      $('div[data-role|="page"]').live('pageshow', function(event) 
      { 
       setTimeout($.mobile.changePage($($(this).attr('NextPage'))), 30000); 
      }); 
     </script> 

     <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script> 
    </head> 
<body> 
    <div data-role="page" id="page1" NextPage='#page2'> 
     <div data-role="content"> 
      <div class="number">4</div> 
     </div> 
    </div> 

    <div data-role="page" id="page2" NextPage='#page3'> 
     <div data-role="content"> 
      <div class='number'>3</div> 
     </div> 
    </div> 

    <div data-role="page" id="page3" NextPage='#page4'> 
     <div data-role="content"> 
      <div class='number'>2</div> 
     </div> 
    </div> 

    <div data-role="page" id="page4" NextPage='#page1'> 
     <div data-role="content"> 
      <div class='number'>1</div> 
     </div> 
    </div> 

    <script type="text/javascript"> 
     $(".number").css(oCSS); 
    </script> 
</body> 
</html> 

答えて

11

構文が間違っています。匿名関数を使用する必要があります。そうしないとJSが直ちに呼び出されます。また、あなたのjQueryも間違っているようです(1つが多すぎます$())。次のようになります。

$('div[data-role|="page"]').live('pageshow', function(event) 
{ 
    // Retrieve attribute of element to be passed to anonymous function 
    var functionParam = $(this).attr('NextPage') 

    setTimeout(function() { 
     // Pass functionParam to function - $(this) will 
     // be out of scope when the function is called 
     $.mobile.changePage(functionParam) 
    }, 30000);​ 
}); 

詳細については、window.setTimeout docsを参照してください。 $(this)

1

あなたの参照がsetTimeout()に(これは匿名関数でDOMWindowExampleされて終わる)は動作しません、あなたは正しく動作する機能のための変数をキャプチャする必要があります。

$('div[data-role|="page"]').live('pageshow', function(event){ 
    var nextPage = $($(this).attr('NextPage')); 
    setTimeout(function(){ 
    $.mobile.changePage(nextPage); 
    }, 30000); 
}); 

Here is a working example on jsfiddle

関連する問題