因此,我有一个附加到几个按钮的常规 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”类型的答案。
编辑:必须将布尔第三个参数传递给 addEventListener 作为 true ,一切都很好。
Use 事件捕获 http://catcode.com/domcontent/events/capture.html,像这样:
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!
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)