开发者

Why will my JQuery only run if I place window load function within?

开发者 https://www.devze.com 2023-04-01 02:34 出处:网络
My following code will not function, unless I place it all $(window).load(function(){ // within here } How can I get my code to run without requiring the above function?

My following code will not function, unless I place it all

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

How can I get my code to run without requiring the above function? Thanks!

My code:

// Player controls
    var timer = null;
    $('#left').mousedown(function() {
                moveLeft(); // Do it now
                timer = setInterval(moveLeft, 5); // Then every 100 ms
          }).mouseup(fu开发者_如何学Pythonnction() {
                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);
});


I'm going to assume you're not trying to get a comparison of why you need $(window).load and not $.ready. Anyway, javascript is run as it's seen. You've got jquery looking up elements (#right, #player, etc) that probably haven't been loaded into the page yet. So, because these elements are not on the page, jQuery can't bind these events to them.

Read this through - it may more thoroughly answer your question. http://api.jquery.com/ready/


If you run the code at the end of the page, rather than in the header, those elements should be loaded by the time the javascript runs.

That said, if your code is comparing the size of images, the images need to be loaded first...


You have to put it below your HTML..

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

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

</body>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号