2011-08-31 31 views
0

我下面的代碼將無法正常工作,除非我把它全部爲什麼我的JQuery只能運行,如果我把窗口加載功能?

$(window).load(function(){ 
// within here 
} 

我怎樣才能讓我的代碼,而無需上述功能運行? 謝謝!

我的代碼:

// Player controls 
    var timer = null; 
    $('#left').mousedown(function() { 
       moveLeft(); // Do it now 
       timer = setInterval(moveLeft, 5); // Then every 100 ms 
      }).mouseup(function() { 
       clearInterval(timer); // And stop it 
      }); 

    function moveLeft() { 
      var nextpos = parseInt($('#player').css('left')) - 5; 
      if (nextpos > 0) { 
       $('#player').css('left', nextpos + 'px'); 
      } 
    } 
    $('#right').mousedown(function() { 
       moveRight(); // Do it now 
       timer = setInterval(moveRight, 5); // Then every 100 ms 
      }).mouseup(function() { 
       clearInterval(timer); // And stop it 
      }); 

    function moveRight() { 
      var nextpos = parseInt($('#player').css('left')) + 5; 
      if (nextpos < PLAYGROUND_WIDTH - 100) { 
       $("#player").css("left", ""+nextpos+"px"); 
      } 
    } 

// Timer 
$(function(){ 
    var timercount = 30; 
     countdown = setInterval(function(){ 
     $("#timer").html(timercount); 
     if (timercount <= 0) { 
      $("#timer").html("TIMES UP"); 
     } 
     timercount--; 
     }, 1000); 
}); 
+0

也就是說包裝物上因爲當您的代碼執行時,頁面可能無法完全加載。你爲什麼不想使用加載函數? – mwcz

+1

爲什麼這是一個問題? – Sparky

回答

2

我會假設你不試圖讓你爲什麼需要$(窗口).load而不是。就緒$比較。無論如何,JavaScript是按照它的運行方式運行的。你有jQuery查找可能還沒有加載到頁面中的元素(#right,#player等)。所以,因爲這些元素不在頁面上,jQuery不能將這些事件綁定到它們。

閱讀這一點 - 它可能會更徹底地回答你的問題。 http://api.jquery.com/ready/

+0

雖然,重新閱讀http://api.jquery.com/ready/頁之後,這也給了一個.load和。就緒之間的差別,所以真的 - 去那裏閱讀:) – Stephen

0

如果運行在頁面的最末尾代碼,而不是在頭,這些元素應該由時加載的JavaScript運行。

也就是說,如果你的代碼是比較圖像的大小,圖像需要先加載中...

0

你必須把你的HTML下面..

<body> 
//your html stuff here that uses the script 

<script type="text/javascript"> 
// the js code here 
</script> 

</body> 
相關問題