javascript - 如何禁用所有点击事件并根据布尔值重新启用它们,该布尔值将来自函数
问题描述
我的 JS 文件中有一些点击事件(超过 100 个),例如代码如下所示。
$(document).on('click', '.a', function(){
alert($(this).text());
});
$(document).on('click', '.b', function(){
alert($(this).text());
});
$(document).on('click', '.c', function(){
alert($(this).text());
});
$(document).on('click', '.d', function(){
alert($(this).text());
});
这只是示例代码,我的 Click 事件做了很多事情,而我无法更改 click 事件代码,
现在我有一个布尔值,我根据某些条件从一个函数中得到它。所以在第一次点击时我想看看这个变量是否为真,那么只有我在特定项目上的点击事件应该触发,否则点击事件不应该触发。
let tre = false;//it could be true or false based on function given below based on some condition.
function test(){
return tre;
}
$(document).on('click', '.a', function(){
alert($(this).text());
});
$(document).on('click', '.b', function(){
alert($(this).text());
});
$(document).on('click', '.c', function(){
alert($(this).text());
});
$(document).on('click', '.d', function(){
alert($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<div class="a">a</div>
<br>
<div class="b">b</div>
<br>
<div class="c">C</div>
<br>
<div class="d">d</div>
</section>
现在我的要求是,如果我单击页面中的任何项目(a、b、c、d)并且如果该变量 tre 为 TRUE,那么只有我的警报应该起作用。
如果需要,我可以将所有点击事件包装在一个函数中,但不能在每个点击事件中添加 if 条件。
解决方案
推荐阅读
- java - 从 swagger 向 REST WebServices 发送请求结束到 401 并且未经授权
- localization - 如何在空手道框架中使用小黄瓜本地化?
- angular - 如何从 Angularfire 承诺创建的可观察对象中捕获错误
- yaml - 如何动态迭代从机器人框架中的yaml文件导入的变量
- javascript - 带有 javascript 的单选按钮
- python - 当我更改权限文件 ir.model.access.csv 并升级模块时,我有一个问题缺少字段“对象”(model_id) 的必需值
- pyiron - 在 HPC 集群中运行 Vasp 作业
- numpy - 如何将形状(4、1、1)的numpy数组重塑为(4、2、1)?
- ios - 使用 SwiftUI 为 UINavigationBar 自定义背景颜色
- macos - 如何通过命令行 mac os 更改 nginx.conf 上的端口?