在任何单击事件处理程序之前调用函数 [英] Calling a function before any click event handler
问题描述
您好我想在每次点击事件处理程序方法之前调用一个函数。
我知道,在点击处理程序方法中我可以先调用我的函数,但这非常麻烦,因为我必须在很多地方执行此操作以及我必须记住以后任何点击事件都一样。
Hi I want to call a function every time before any click event handler method. I know, inside the click handler method I can call my function first, but this quite cumbersome as I have to do this at so many place as well as I have to keep in mind the same for any future click events.
推荐答案
您可以在文档
对象上设置捕获事件处理程序(或者任何公共父级),它将在单个对象的事件处理程序之前首先被调用。 capture
是 .addEventListener()
的第三个参数,通常是可选的,默认为 false
,但如果你在父母身上传递 true
,那么将首先调用事件处理程序。
You can set a capture event handler on the document
object (or any common parent) and it will be called first before the event handler on the individual object. capture
is the third argument to .addEventListener()
which is normally optional and defaults to false
, but if you pass true
on a parent, then the event handler will be called first.
以下是一个示例:
document.addEventListener("click", function() {
log("document capture click");
}, true);
document.getElementById("target").addEventListener("click", function() {
log("element click");
}, false);
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
<div id="target">Some text to click on</div>
这是一个有助于理解捕获标记的相关问题:无法了解addEventListener中的useCapture属性
Here's a related question that helps to understand the capture flag: Unable to understand useCapture attribute in addEventListener
这篇关于在任何单击事件处理程序之前调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!