onmouseover doesn't work when using javascript to add img tag on IE

前端 未结 4 645
闹比i
闹比i 2021-01-13 14:24

I need some javascript code that dynamically adds an img tag to a div, and the img tag needs onmouseover and onmouseout handlers.

I have it working on Firefox. But

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 15:09

    img.setAttribute('src', 'http://sstatic.net/so/img/logo.png');
    

    Don't use setAttribute on an HTMLElement, at all. There are bugs in it in Internet Explorer and it doesn't get you anything compared to the more readable DOM Level 1 HTML alternative:

    img.src= 'http://sstatic.net/so/img/logo.png';
    

    The essential problem with setAttribute on IE is that it works the same as normal property access, even when the property has a different name or type to the attribute. So this:

    img.setAttribute('onmouseover', "alert('mouseover')");
    

    is the same as saying:

    img.onmouseover= "alert('mouseover')";
    

    which makes no sense: the onmouseover property is, like all event handlers, supposed to be a function, not a string. Assign a function instead:

    img.onmouseover= function() {
        alert('mouseover');
    };
    

    and then you've also got rid the nasty eval-style practice of putting code inside a string. Hooray!

    As for addEventListener, you can use it if you add a fallback attachEvent call for IE (which has its own crazy event listener system). But in the common case where you only ever have one listener for each element it is much easier to stick with the old-school supported-by-every-browser onsomething-assigning event handlers.

提交回复
热议问题