javascript - 如何解决 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>
解决方案
当您单击按钮 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>
推荐阅读
- c++ - 在 WM_CREATE 中加载多个位图的 C++ Win32 不会加载
- python - Python/Kivy-iOS/Xcode 环境的模块导入问题
- sql - 如何在多个条件下计算值以及如何设计数据库?
- makefile - make 不解析目标名称的绝对路径
- python-3.x - CSV 输出只取第一组字典
- mongodb - 尝试在 MacOS 上安装 mongoldb
- excel - 利用 while 循环在 Excel 电子表格中创建组合框
- powershell - 将 Set-PnPListItem 与“发布图像”类型一起使用
- android - FileNotFoundException SQLite 数据库 Android
- swiftui - 文本视图的 lineBreakMode 是否有 SwiftUI 等效项?