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