2012-05-01 56 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似乎也不正確(太多的$())。它應該是:

$('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瞭解更多信息。

1

您對$(this)參考是不行的(這在匿名函數最終被DOMWindowExample)在setTimeout(),你需要捕捉的功能,正確的行爲變量。

$('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