Add event listener in javascript for IE 7
I want to make list of menu by using images. Each menu has two images (filename.jpg & filename_active.jpg). Everytime i put the mouse over its image, the image will change to the other one. It works okay in Firefox and chrome, but i have problems in IE 7 and lower. The problem is, javascript will only read the last part (in this case, he will re开发者_开发技巧ad third menu only). The code that i will show below is only part of javascript code for in IE. Let me show my code :
HTML :
<ul>
<li class="caresoul_menu active" id="menuli_first"><a href="first.php"><img src="img_first_active.jpg" /></a></li>
<li class="caresoul_menu" id="menuli_two"><a href="two.php"><img src="img_two.jpg" /></a></li>
<li class="caresoul_menu" id="menuli_three"><a href="three.php"><img src="img_three.jpg" /></a></li>
Javascript :
var caresoul_menu = Dom.getElementsByClassName('caresoul_menu', 'li');
if(caresoul_menu.length > 0) {
for(var im in caresoul_menu) {
if (caresoul_menu[im].attachEvent) {
caresoul_menu[im].attachEvent('onmouseover', function(){
var liId = caresoul_menu[im].getAttribute('id').split('menuli_')[1];
caresoul_menu[im].firstChild.firstChild.setAttribute('src','/image/'+liId+'_active.png');
})
}
}
}
I'll explain: when the mouseover event is fired, the for
loop has already ended so the im
variable has the last known value and the value is the same for all <li>
elements. Try something like:
if (caresoul_menu[im].attachEvent) {
(function (that) {
that.attachEvent('onmouseover', function(){
var liId = that.getAttribute('id').split('menuli_')[1];
that.firstChild.firstChild.setAttribute('src','/image/'+liId+'_active.png');
});
})(caresoul_menu[im]);
}
Do you really need to use attachEvent
? If you'd attach event listeners the DOM0 way (element.onmouseover = function(){}
), you could use the this
keyword in the event listener.
精彩评论