JavaScript - 勾选所有“点击”事件 [英] JavaScript - Hook in some check on all 'click' events
问题描述
所以我有一个常规的onclick事件附加到几个按钮,每个处理onclick事件的函数都做了不同的事情(所以我不能为这两个事件重用相同的函数)。
So I have a regular onclick event attached to a few buttons, each function that handles the onclick event does something different (so I can't reuse the same function for both events).
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事件。
I'm writing duplicate code for this 'disabled' class check, I want to eliminate this by hooking in some common onclick check then fire the regular onclick event if that check passes.
我知道下面的内容不起作用,但我想它会说明我要做的事情:
I know the below won't work but I think it will illustrate what I'm trying to do:
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类型的答案。
I'm not using any JavaScript library and I don't plan to, in case someone comes up with 'Just use jQuery' type answers.
编辑:必须将布尔第三个参数传递给addEventListener为真,一切都很好。
Had to pass boolean third argument to addEventListener as true and everything is fine.
推荐答案
使用事件捕获 ,像这样:
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 - 勾选所有“点击”事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!