Javascript 检测 HTML 元素上可用的事件处理程序

发布于 2024-09-01 18:04:48 字数 519 浏览 2 评论 0原文

有没有办法检测 HTML 元素本机可用的事件处理程序?

例如:

isAvailable(img.onload) === true;    // All browsers
isAvailable(script.onload) === true; // Non-IE only (Webkit, Firefox, Opera)
isAvailable(link.onload) === true;   // IE (and I think Opera) only

理想情况下,我想在我的脚本中进行功能检测,如果 onload 可用于元素使用它,否则回退。目前我必须进行浏览器分叉(基于 IE),这很烦人,因为 IE 可能开始支持 script.onload,而 Webkit/Firefox 可能开始支持 link.onload

不幸的是,分配 element.onload 会使事件不再“未定义”,无论它最终是否会触发。

Is there a way to detect what event handlers are available natively for an HTML element?

For example:

isAvailable(img.onload) === true;    // All browsers
isAvailable(script.onload) === true; // Non-IE only (Webkit, Firefox, Opera)
isAvailable(link.onload) === true;   // IE (and I think Opera) only

Ideally I want to do feature detection in my script, where if onload is available for an element to use that, otherwise fallback. Currently I am having to do browser forks (based on IE) which is annoying as IE may start supporting script.onload, and Webkit/Firefox may start supporting link.onload.

Unfortunately assigning element.onload makes the event no longer 'undefined', regardless of whether it will eventually fire or not.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

青朷 2024-09-08 18:04:48

编辑见下文,这不起作用。)您可以检查该元素是否具有onload属性:

var img = document.createElement('img');
alert("img onload? " + ('onload' in img));
var script = document.createElement('script');
alert("script onload? " + ('onload' in script));

在IE7上,我得到true对于imgfalse对于script

编辑 这不适用于 Firefox。留下这个只是为了让其他人不要走同样的路。

(Edit See below, this doesn't work.) You can check whether the element has an onload property:

var img = document.createElement('img');
alert("img onload? " + ('onload' in img));
var script = document.createElement('script');
alert("script onload? " + ('onload' in script));

On IE7, I get true for the img, and false for the script.

Edit This doesn't work for Firefox. Leaving this just so others don't go down the same path.

云柯 2024-09-08 18:04:48

我不确定这是否是您所要求的,但这会让您知道您是否有可用于给定对象的特定方法或属性。

var apple = new Object;
    apple.load = function() { alert("I am a method.") };
    apple.color = "red"

function isAvailable(obj, mp) { 
    // obj = element to test for method or property. 
    // mp = name of method or property. 

    if (obj[mp]) {
        return true;
    } else {
        return false;
    }
}

if (isAvailable(apple, "color")) {
    alert("apple object has a 'color' property");
}

if (isAvailable(apple, "load")) {
    alert("apple object has a 'load' method");
}

编辑:重新编写答案以显示示例。

I am not sure if this is what you were asking for, but this will let you know if you have a specific method or property available for a given object.

var apple = new Object;
    apple.load = function() { alert("I am a method.") };
    apple.color = "red"

function isAvailable(obj, mp) { 
    // obj = element to test for method or property. 
    // mp = name of method or property. 

    if (obj[mp]) {
        return true;
    } else {
        return false;
    }
}

if (isAvailable(apple, "color")) {
    alert("apple object has a 'color' property");
}

if (isAvailable(apple, "load")) {
    alert("apple object has a 'load' method");
}

Edit: Re-worked the answer to show an example.

半﹌身腐败 2024-09-08 18:04:48

我以前做过类似的事情;当在 iPhone 上为手机间隙编写内容时,根据您是否在模拟器中或在不同版本的设备上运行应用程序,您通常有不同的处理程序来处理输入按钮(以及大多数其他事情)的点击 - 所以在顶部我只是对我的脚本进行快速检查;

var m_clickEvent = ''; 

if ( $('input').click != 'undefined')
   m_clickEvent = 'click'
else if ( $('input').tap != 'tap')
   m_clickEvent = 'tap'
else if ( $('input').touchstart!= 'touchstart')
   m_clickEvent = 'touchstart'
else 
   // some kind of error handling..

然后我可以继续绑定我的事件处理程序;

$('.myButton').bind(m_clickEvent, function(e) { ... });

I've done something like this before; when writing stuff for phone gap on the iphone, depending if you run the app in the simulator or on different versions of the device, you often have different handlers for handling the click of input buttons (and most other things)- so at the top of my script i just do a quick check;

var m_clickEvent = ''; 

if ( $('input').click != 'undefined')
   m_clickEvent = 'click'
else if ( $('input').tap != 'tap')
   m_clickEvent = 'tap'
else if ( $('input').touchstart!= 'touchstart')
   m_clickEvent = 'touchstart'
else 
   // some kind of error handling..

then i can go ahead and bind my event handler;

$('.myButton').bind(m_clickEvent, function(e) { ... });
山色无中 2024-09-08 18:04:48

以下是从 Modernizr 进行事件检测的方式中提取的示例:

var tmp = document.createElement('script'); 
tmp.setAttribute('onload', '');
isSupported = typeof tmp.onload == 'function';

Here's an example destilled from the way Modernizr does event detection:

var tmp = document.createElement('script'); 
tmp.setAttribute('onload', '');
isSupported = typeof tmp.onload == 'function';
挖鼻大婶 2024-09-08 18:04:48

我过去这样做的一种方法是使用旧的“for in”循环,并检查每个键值以查看它是否以“on”开头(我见过的每个本机事件处理程序都是这样开始的。 .)所以,例如:

var el = document.querySelector("*"), //this is the element (use whatever selector text)
elEventHandlers = [];                 //set up an array to hold 'em all

for (var prop in el)                  //loop through each prop of the element
    if (prop.substring(0,2)=="on")    //if the prop starts with "on" it's an event handler
        elEventHandlers.push(prop);   //so, add it to the array

console.log(elEventHandlers);         //then dump the array to the console (or whatever)

瞧!现在您知道可以在该元素上注册哪些事件处理程序了!

One way I've done this in the past is to use the old "for in" loop, and check each key value to see if it starts with "on" (every native event handler I've ever seen starts this way...) So, for example:

var el = document.querySelector("*"), //this is the element (use whatever selector text)
elEventHandlers = [];                 //set up an array to hold 'em all

for (var prop in el)                  //loop through each prop of the element
    if (prop.substring(0,2)=="on")    //if the prop starts with "on" it's an event handler
        elEventHandlers.push(prop);   //so, add it to the array

console.log(elEventHandlers);         //then dump the array to the console (or whatever)

voila! Now you know what event handlers can be registered on that element!

酒解孤独 2024-09-08 18:04:48

试试这个:

var d = document.createElement('div');

if(d.hasOwnProperty('onclick')) {
    //then onclick is supported
}

您还可以循环遍历 div 的(或采用任何其他 HTML 元素)属性来动态检查它:

var d = document.createElement('div'),
   el = 0;

for(el in d) {
    if(d.hasOwnProperty(el)) {
        console.log(d[el]); //or do anything else you like
    }
}

您可以在 mozilla 的开发博客

Try this one:

var d = document.createElement('div');

if(d.hasOwnProperty('onclick')) {
    //then onclick is supported
}

you could also loop through div's(or take any other HTML element) properties to dynamically check it:

var d = document.createElement('div'),
   el = 0;

for(el in d) {
    if(d.hasOwnProperty(el)) {
        console.log(d[el]); //or do anything else you like
    }
}

You could check more on hasOwnProperty on mozilla's dev blog

一绘本一梦想 2024-09-08 18:04:48
isEventSupported =
    function(tag, event){
    return document.createElement(tag)[event]===null;
    };

>> isEventSupported("script", "onload"); 
true //on my current browser

有一些关于此事件支持的虚假报告,甚至来自像...这样的退伍军人,我们不提名字 - 但不明显的是,onload 事件很可能不会在 IMG 元素、SCRIPT 元素和类似元素上触发,因为来源已经是cashed 和从现金中提取资源的元素不会触发 onload 事件。

例外:即使在处理已兑现的文件时,文档元素也会触发 onload 事件,因为它取决于就绪状态完成。

isEventSupported =
    function(tag, event){
    return document.createElement(tag)[event]===null;
    };

>> isEventSupported("script", "onload"); 
true //on my current browser

There are, false reports on this event support even from veterans like..., let's not mention names - but it is NOT obvious that the onload event will most probably not fire on IMG elements SCRIPT elements and similar, because the source has already been cashed and Elements whose resources are being drawn from the cash will not fire the onload event.

Exception: the document element will fire the onload event, even when working with cashed files, because it depends on readystate complete.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文