开发者

How to detect if the event is a browser event or not

How would you test if an event is a browser event (e.g. click, load, blur etc) based on its name (e.g. click)? (and no I'm not using jQuery/mootools/prototype/dojo)

UPDATE:

In this function I attach browser events (click and load) for example:

observe: function(elements, eventName, callback) {
  if (!(elements.length != null)) {
    elements = [elements];
  }
  return this.each(elements, function(e) {
    if (helper.hooks.eventObserved != null) {
      helper.hooks.eventObserved(eventName, callback, e);
    }
    if (typeof e === 'string') {
      e = this.el(e);
    }
    if (e.addEventListener) {
      return e.addEventListener(eventName, callback, false);
    } else if (e.attachEvent) {
      return e.attachEvent("on" + eventName, callback);
    }
  });
},

And this fires the event:

fire: function(elements, eventName) {
  if (!(elements.length != null)) {
    elements = [elements];
  }
  return this.each(elements, function(e) {
    var evt;
    if (document.createEventObject != null) {
      evt = document.createEventObject();
      return e.fireEvent("on" + eventName);
    } else {
      evt = document.createEvent('HTMLEvents');
      evt.initEvent(eventName, true, true);
      return !e.dispatchEvent(evt);
    }
  });
},

Bu开发者_开发技巧t what I want is to test if the event exists for example click is a browser event but login isn't so how would I test that?


Check out this solution by Juriy Zaytsev (live demo).

jQuery itself uses it.


You could check to see if the function/object element["on"+event] exists:

<a href="http://www.google.com" id="myAnchor">test</a>
<script>

function doesElementHaveEvent(element, event){
    return (typeof element["on"+event] != typeof undefined);
}

alert(doesElementHaveEvent(document.getElementById("myAnchor"), "click")); // true
alert(doesElementHaveEvent(document.getElementById("myAnchor"), "login")); // false
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜