Why doesn't IE8 handle iframe onload events?

后端 未结 4 1005
你的背包
你的背包 2021-01-01 02:13

Sample code:







        
4条回答
  •  [愿得一人]
    2021-01-01 02:57

    It seems you can't add a load listener to an iFrame in IE using the DOM property once the page has loaded.

    But you can use attachEvent, so:

    function on_iframe_load() {
        function foo() {
            alert('Thanks for the visit!');
        };
        var el = document.getElementById('iframe_a');
    
        if (el.attachEvent) {
          el.attachEvent('onload',foo);
        } else if (el.addEventListener) {
          el.addEventListener('load', 'foo', false);
        }
    }
    

    I was testing in IE 6 and reversed the usual test order so that attachEvent is used in preference to addEventListener. You may want to test more recent versions of IE to see if the opposite order works and also test other IE–like browsers such as Opera.

    Edit

    Modified the code after testing (silly me) to use addEventListener. Here's something that works in IE and others:

    function on_iframe_load() {
        function foo() {
            alert('Thanks for the visit!');
        };
        var el = document.getElementById('iframe_a');
    
        if (el.attachEvent) {
          el.attachEvent('onload',foo);
    
        } else {
          el.onload = foo;
        }
    }
    

    And if you use an onload attribute in the markup, you don't need to add the listener using script.

提交回复
热议问题