小编Joh*_*fee的帖子

JQuery - 连续多次调用函数时,为什么只有最后一次调用的回调才能正确执行?

  1. 有一个函数在完成时触发回调;
  2. 我连续2或3次调用此函数;
  3. 只有最后一次调用的回调才能达到预期的效果;

以下描述和代码举例说明了真实情况.

我有三对div.我需要切换每对中的一个div并在其对不再可见时更改剩余可见div的状态.

然后,我创建了一个函数隐藏div并更改另一个div的背景颜色.我这样做是因为每当用户点击按钮显示描述和其他非必要项目时,我都想调用此功能.

不幸的是,结果不是我预期的结果.如果用户多次调用该函数,而不让函数完成它的任务,则只有最后一个绑定的回调才能正常运行,其他的不会改变div的背景颜色或者会不同步由于延迟而与另一个div.

这是javascript:

function toggleLayer(layerId,layerId2) {
    //element1 is the first div of the pair. The one to be hidden.
    element1 = $("#"+layerId);
    //element2 is the second div of the pair. The background-color of this one will be changed when the element1 is hidden.
    element2 = $("#"+layerId2);

    //Hiding the first div
    element1.toggle("slow",function() {
        //Changing the color of the second div
        element2.toggleClass("blue");
    });
}
Run Code Online (Sandbox Code Playgroud)

这是完整的HTML,只需复制并粘贴到测试:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta …
Run Code Online (Sandbox Code Playgroud)

javascript jquery callback simultaneous-calls

3
推荐指数
1
解决办法
2552
查看次数

标签 统计

callback ×1

javascript ×1

jquery ×1

simultaneous-calls ×1