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

南笙酒味 提交于 2019-12-18 17:05:23

问题


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.

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 loadedmetadata event handler exists or not to run the function only one time in each browser.

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


回答1:


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.

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



来源:https://stackoverflow.com/questions/3898055/how-to-check-if-an-event-handler-exist-using-jquery-or-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!