首页 > 解决方案 > 如何解决 jQuery 代码中的递归问题

问题描述

我从事游戏项目有一段时间了。我使用过引导程序和 jQuery。但为了简单起见,这就是我不明白的代码的样子。我希望通过单击并仅单击项目 A,项目 B 在单击后会显示并消失。我添加了一条指令,每次单击项目后都会在控制台中显示一条消息并观察会发生什么!

let elt_boxOne = $("#bx_one");
let elt_boxTwo = $("#bx_two");
elt_boxTwo.hide();

elt_boxOne.click($.proxy(function() {
  elt_boxTwo.show();
  elt_boxTwo.click($.proxy(function() {
    console.log("Hello world");
    elt_boxTwo.hide();
  }, this));
}, this));

/*As you can see the first time has no problem but if we try the second time there will be two messages and the third click will show three etc... I mean what the hell is going on???*/
#bx_one {
  width: 200px;
  height: 50px;
  background-color: red;
  text-align: center;
  font-weight: bold;
}

#bx_two {
  width: 200px;
  height: 50px;
  background-color: orange;
  text-align: center;
  font-weight: bold;
}
<div id="bx_one">Box one</div>
<div id="bx_two">Box two</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

标签: javascriptjqueryrecursion

解决方案


当您单击按钮 1 时,您将多次初始化单击侦听器。您必须将其移到外部,独立于第一个单击处理程序......像这样:

顺便说一句,你不需要代理,如果你需要里面的上下文,你可以使用箭头函数。

let elt_boxOne = $("#bx_one");
let elt_boxTwo = $("#bx_two");

elt_boxTwo.hide();

elt_boxOne.click(() => {
    elt_boxTwo.show();
});

elt_boxTwo.click(() => {
    console.log("Hello world");
    elt_boxTwo.hide();
});
#bx_one {
    width: 200px;
    height: 50px;
    background-color: red;
    text-align: center;
    font-weight: bold;
}
#bx_two {
    width: 200px;
    height: 50px;
    background-color: orange;
    text-align: center;
    font-weight: bold;
}
<div id="bx_one">Box one</div>
<div id="bx_two">Box two</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读