开发者

simple code with plain js : addEventListener doesn't respond

i just wanted to make a test, i'm used to work on jQuery but not on "plain" javascript, i tried to bind this event, but i've got no answer from the event, i just created a link and a script tag in the html code, with :

var li = document.getElementById('first');

li.addEventListener('onMouseover', function(){

alert('ok');

})

Can you please tell me what is wrong with it?开发者_Go百科 i don't see the mistake.

Thanks


First, you need to drop the "on" part for addEventListener(). Second, the event name needs to be all lower case. Third, you were missing the third parameter, which is Boolean indicating whether to handle the event in the capturing phase rather than the bubbling phase (if in doubt, use false).

The other issue you need to consider is that IE <= 8 does not support addEventListener(), so you need to include an IE-specific fallback using the proprietary attachEvent() method.

With all this, your example becomes:

var li = document.getElementById('first');
if (typeof li.addEventListener != "undefined") {
    li.addEventListener('mouseover', function() {
        alert('ok');
    }, false);
} else if (typeof li.attachEvent != "undefined") {
    li.attachEvent('onmouseover', function() {
        alert('ok');
    });
}

The easiest cross-browser solution is the so-called DOM0 method, using the element's onmouseover property. However, this has the disadvantage of only allowing one event listener per event per element and is therefore potentially susceptible to being overridden by other code.

li.onmouseover = function() {
    alert('ok');
};


You can assign the handler function directly to the onmouseover property of the selected element in the DOM:

var lis = document.getElementById('first');
lis.onmouseover = function() {
    alert('yo');
};

On jsFiddle: http://jsfiddle.net/entropo/YMGAy/

Docs:

  • https://developer.mozilla.org/en/DOM/element.addEventListener#Older_way_to_register_event_listeners
  • https://developer.mozilla.org/en/DOM/element.onmouseover

Edit:
Here it is too using addEventListener...

li = document.getElementById('first');
li.addEventListener('mouseover', function(e) {
    alert('ok');
}, false);

http://jsfiddle.net/entropo/7FvZ7/
You were missing the last argument to addEventListener (for useCapture)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜