javascript 如何使用 jQuery 或 JS 检查事件处理程序是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3898055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:36:22  来源:igfitidea点击:

How to check if an event handler exist using jQuery or JS?

javascriptjqueryeventsbrowser

提问by Omar Abid

I want to check if an event is available or not before binding a function to it. The problem is that Google Chrome support the event "loadedmetadata" in the Video element while FireFox don't.

我想在绑定函数之前检查事件是否可用。问题是 Google Chrome 支持 Video 元素中的事件“loadedmetadata”,而 FireFox 不支持。

I did the following

我做了以下

$('video').bind('loadedmetadata', videoloaded);
videoloaded();

It worked well in Firefox but when I tried in Chrome, the function was executed twice (which is logical). I want to check if loadedmetadataevent handler exists or not to run the function only one time in each browser.

它在 Firefox 中运行良好,但是当我在 Chrome 中尝试时,该函数执行了两次(这是合乎逻辑的)。我想检查loadedmetadata事件处理程序是否存在,以便在每个浏览器中只运行一次该函数。

If such possibility doesn't exist, any intelligent work around for this?

如果这种可能性不存在,是否有任何智能解决方法?

采纳答案by BrunoLM

Check the $video.data("events")if this object contains your event, since you are using .bindall events of this element will be stored in this object.

检查$video.data("events")此对象是否包含您的事件,因为您正在使用.bind此元素的所有事件都将存储在此对象中。

var $video = $("#video");
var $ve = $video.data("events");

// checking if a `loadedmetadata` object exists in `data("events")`
if ($ve != null && typeof($ve.loadedmetadata) !== undefined)
{
    // has loadedmetadata event
}

Full working example on jsFiddle

jsFiddle 上的完整工作示例