在任何单击事件处理程序之前调用函数 [英] Calling a function before any click event handler

查看:51
本文介绍了在任何单击事件处理程序之前调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想在每次点击事件处理程序方法之前调用一个函数。
我知道,在点击处理程序方法中我可以先调用我的函数,但这非常麻烦,因为我必须在很多地方执行此操作以及我必须记住以后任何点击事件都一样。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆