IE8为什么不处理iframe onload事件?

Mor*_*ori 5 html javascript iframe internet-explorer-8

示例代码:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function on_iframe_load() {
    document.getElementById('iframe_a').onload = function() {
        alert('Thanks for the visit!');
    };
}
</script>
</head>
<body>
<iframe name="iframe_a" id="iframe_a"></iframe>
<a href="http://www.example.com/" target="iframe_a" onclick="on_iframe_load();">Go!</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

它适用于所有主流浏览器没有问题,但IE8(可能还有以前的版本)不理解它.

更新:刚刚提出了一个解决方案,但我不确定它是否正确编码.请查阅:

<!DOCTYPE html>
<html>

    <head>
        <title></title>
        <script>
            var clicked = false;

            function activate() {
                clicked = true;
            }

            function pop() {
                if (clicked) {
                    alert('Thanks for the visit!');
                };
            }
        </script>
    </head>

    <body>
        <iframe name="iframe_a" onload="pop();"></iframe>
        <a href="http://www.example.com/" target="iframe_a" onclick="activate();">Go!</a>

    </body>

</html>
Run Code Online (Sandbox Code Playgroud)

Rob*_*obG 2

一旦页面加载,您似乎无法使用 DOM 属性向 IE 中的 iFrame 添加加载侦听器。

\n\n

但你可以使用attachEvent,所以:

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

我在 IE 6 中进行测试并颠倒了通常的测试顺序,以便attachEvent优先使用addEventListener. 您可能想要测试更新版本的 IE,看看相反的顺序是否有效,并测试其他类似 IE\xe2\x80\x93 的浏览器,例如 Opera。

\n\n

编辑

\n\n

测试后修改代码(愚蠢的我)以使用addEventListener. 这是在 IE 和其他浏览器中有效的东西:

\n\n
function on_iframe_load() {\n    function foo() {\n        alert('Thanks for the visit!');\n    };\n    var el = document.getElementById('iframe_a');\n\n    if (el.attachEvent) {\n      el.attachEvent('onload',foo);\n\n    } else {\n      el.onload = foo;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您在标记中使用 onload 属性,则无需使用脚本添加侦听器。

\n