简体   繁体   English

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

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

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). 它在Firefox中运行良好,但是当我在Chrome中尝试时,该函数执行了两次(这是合乎逻辑的)。 I want to check if loadedmetadata event handler exists or not to run the function only one time in each browser. 我想检查是否存在loadedmetadata事件处理程序,或者在每个浏览器中仅运行一次该函数。

If such possibility doesn't exist, any intelligent work around for this? 如果不存在这种可能性,那么有什么明智的解决方法吗?

Check the $video.data("events") if this object contains your event, since you are using .bind all 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上的完整工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM