2

所以我有一个常规的 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
};

我正在为此“禁用”类检查编写重复的代码,我想通过挂钩一些常见的 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”类型的答案。

编辑:必须将布尔第三个参数作为 true 传递给 addEventListener,一切都很好。

4

3 回答 3

4

Use event capturing, like so:

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!
);
于 2012-12-10T13:47:34.723 回答
1

您可以创建一个接收回调的通用函数:

//check everything here
function handleOnclick(callback) { 
    if(this.classList.contains("disabled")) {
       return false;
    } else {
     callback(); //callback here
    }
}

//and now on every onclick, just pass the custom behavior

element1.onclick = function() {
   handleOnClick(function() { 
        console.log('element1 onclick fire'); // For example hide a div
    });
};


element2.onclick = function() {
   handleOnClick(function() { 
        console.log('element2 onclick fire'); // For example ajax request
    });
};

Edit Based on your latest comment, let me know if this rewrite works for you... only one biding this time.

element1.customFunction = function() {
   handleOnClick(function() { 
        console.log('element1 onclick fire'); // For example hide a div
    });
};

element2.customFunction = function() {
   handleOnClick(function() { 
        console.log('element2 onclick fire'); // For example ajax request
    });
};

document.addEventListener('click', function() {
   //1. grab the element
   //2. check if it has the customFunction defined
   //3. if it does, call it, the check will be done inside
};
于 2012-12-10T13:41:19.650 回答
1

Sounds like you need to set the capture flag to true and then use .stopPropagation() on the event if a certain condition is met at the target, f.ex:

document.addEventListener('click', function(e) {
    if ( condition ) {
        e.stopPropagation();
        // do soemthing else, the default onclick will never happen
    }
}, true);​​​​​​​​​​​​​​​​​​​​​​

Here is a demo: http://jsfiddle.net/v9TEj/

于 2012-12-10T13:44:31.617 回答