首页 > 解决方案 > 如何禁用所有点击事件并根据布尔值重新启用它们,该布尔值将来自函数

问题描述

我的 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 条件。

标签: javascripthtmljquery

解决方案


推荐阅读