使用JavaScript或jQuery如何检查窗口上是否存在事件?
问题描述:
我已经将一个事件附加到'window'对象,我想通过代码检查它是否存在。
I've attached an event to the 'window' object, and I would like to check that it's there via code.
window.addEventListener('beforeunload', function(e){ /*...*/ }, false)
尝试
我尝试过简单的jQuery,没有运气。我对 jsFiddle 进行了更多尝试。
Attempts
I've tried the simple, and jQuery, without luck. I have more attempts up on jsFiddle.
window.beforeunload //is undefined as is window.onbeforeunload
$(window).data('events') //not working either
这可能吗?
有类似的问题(这里和这里)关于DOM和其他元素,但是我尝试过的方法都没有奏效。
There are similar questions (here and here) about the DOM, and other elements, but none of the approaches in those that I have tried have worked.
答
你可以使用
operator ...
You can use the in
operator...
'onbeforeunload' in window; // true (if supported)
如果支持,该属性将存在,但值将为 null
。