JavaScript - 对所有 'click' 事件进行一些检查

标签 javascript

所以我有一个常规的 onclick 事件附加到几个按钮,每个处理 onclick 事件的函数都做不同的事情(所以我不能为两个事件重用相同的函数)。

element1.onclick = function() {
    if(this.classList.contains('disabled') {
        return false;
    }
    // For example make an AJAX call
};

element2.onclick = function() {
    if(this.classList.contains('disabled') {
        return false;
    }
    // For example hide a div
};

我正在为这个“禁用的”类检查编写重复代码,我想通过 Hook 一些常见的 onclick 检查来消除它,然后在检查通过时触发常规的 onclick 事件。

我知道下面的内容行不通,但我认为它将说明我正在尝试做的事情:

document.addEventListener('click', function() {
    // 1. Do the disabled check here
    // 2. If the check passes delegate the event to the proper element it was invoked on
    // 3. Otherwise kill the event here
});

我没有使用任何 JavaScript 库,我也不打算使用,以防万一有人提出“只需使用 jQuery”类型的答案。

编辑:必须将 bool 值第三个参数作为 true 传递给 addEventListener,一切正常。

最佳答案

使用event capturing ,像这样:

document.addEventListener('click', function(event) {
    if (/* your disabled check here */) {
      // Kill the event
      event.preventDefault();
      event.stopPropagation();
    }

    // Doing nothing in this method lets the event proceed as normal
  },
  true  // Enable event capturing!
);

关于JavaScript - 对所有 'click' 事件进行一些检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13802025/

相关文章:

javascript - AngularJS 先删除 ref 文档,然后再删除父文档

javascript - ng-repeat 不绑定(bind) ng-model 对象数组

javascript - 如何将 "Please Select"添加到 Javascript 下拉菜单

javascript - 单击一个项目,从其他项目中添加和删除类

javascript - 如何使用 VSTS Node API 设置积压迭代?

javascript - 如果 child 不在 parent 内部,则在悬停 parent 时保持对 child 的悬停效果

javascript - Angular : passing index of object array from ng-repeat to access object data

javascript - 如何在 angularjs 中将 ng-class 与服务中的 bool 值一起使用?

php - 将 Javascript 放入 php 中

javascript - 在模块函数上使用 bind 后未定义 this