JQuery,setTimeout不起作用 [英] JQuery, setTimeout not working

查看:512
本文介绍了JQuery,setTimeout不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是JQuery的新手,在让我的ajax示例工作的过程中,我使用setTimeout停滞不前。我把它分解到应该添加的地方。每秒钟到div。

I'm still new to JQuery, on the way to getting my ajax example to work i got stalled with setTimeout. I have broken it down to to where it should add "." to the div every second.

相关代码分为两个文件。

The relevant code is in two files.

index.html

<html><head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript' src='myCode.js'></script>
</head>
<body>
<div id='board'>Text</div>
</body>
</html>

myCode.js

(function(){
   $(document).ready(function() {update();});

   function update() { 
      $("#board").append(".");
      setTimeout('update()', 1000);     }
 })();

myCode.js文件工作正常,update()第一次运行但从未再次运行。

the myCode.js file works alright and "update()" runs the first time through but never again.

推荐答案

这里有几个问题。

首先,您要在匿名函数中定义代码。这个结构:

Firstly, you're defining your code within an anonymous function. This construct:

(function() {
  ...
)();

做两件事。它定义了一个匿名函数并调用它。这样做有范围原因,但我不确定这是你真正想要的。

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

你将代码块传递给 setTimeout() 。问题是 update()在执行时不在范围内。但是,如果你传入一个函数指针,那么它可以工作:

You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

(function() {
  $(document).ready(function() {update();});

  function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);     }
  }
)();

因为函数指针 update 在范围内那个街区。

because the function pointer update is within scope of that block.

但就像我说的那样,不需要匿名功能,所以你可以像这样重写它:

But like I said, there is no need for the anonymous function so you can rewrite it like this:

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout(update, 1000);     }
}

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);     }
}

这两项都有效。第二个可行,因为代码块中的 update()现在在范围内。

and both of these work. The second works because the update() within the code block is within scope now.

我也更喜欢 $(function(){...} 缩短块形式,而不是在<$ c $中调用 setTimeout() c> update()你可以使用 setInterval() 而不是:

I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

$(function() {
  setInterval(update, 1000);
});

function update() {
  $("#board").append(".");
}

希望清除它。

这篇关于JQuery,setTimeout不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆