simple code with plain js : addEventListener doesn't respond
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.
ThanksFirst, 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
)
精彩评论