0

示例代码:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<iframe name="iframe_a" onload="alert('Thanks for the visit!');"></iframe>
<a href="http://www.example.com/" target="iframe_a">Go!</a>
</body>
</html>

我希望在单击链接后以及 iframe 完成加载后看到警报消息。但现在它也出现在初始页面加载中。我怎样才能实现它以便它在 IE8+ 中工作?

刚刚想出了一个简单的解决方案:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<iframe id="iframe_a" name="iframe_a" onload="if(this.className=='active'){alert('Thanks for the visit!');};"></iframe>
<a href="http://www.example.com/" target="iframe_a" onclick="document.getElementById('iframe_a').className='active';">Go!</a>
</body>
</html>
4

4 回答 4

0

当 iframe 在 DOM 中时,没有(理智的)方法可以防止加载 iframe。在加载之前将 onload 添加到 iframe 应该可以解决您的问题:

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<iframe id="myIframe" name="iframe_a"></iframe>
<a href="#" onclick="$('#myIframe').load(function() {alert('Thanks for the visit!');}); $('#myIframe').attr('src','http://www.example.com/')">Go!</a>
</body>
</html>
于 2012-10-14T04:24:59.410 回答
0
<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
        <script type="text/javascript">
            window.addEvent = (function() {
                var evnt = window.addEventListener ? "addEventListener" : "attachEvent",
                    pre = evnt === "attachEvent" ? "on" : "";

                return function (ele, evnt, func, bub) {
                    ele[evnt](pre + evnt, func, bub);
                }
            }());
            addEvent(window, "load", function() {
                addEvent(document.getElementById("myIframe"), "load", function() {
                    alert("Loaded!");
                });
            });
        </script>
    </head>
    <body>
        <iframe id="myIframe" name="iframe_a"></iframe>
        <a href="..." target="iframe_a">GO!</a>
    </body>
</html>
于 2012-10-14T04:31:00.127 回答
0

使用这种方式,在 IE 8 中工作:

<iframe id="myIframe" name="iframe_a"></iframe>
<a href="http://www.example.com/" target="iframe_a" onclick="alert('Thanks for the visit!');">Go!</a>
于 2012-10-14T04:33:20.013 回答
0

这个很有趣,但它可以满足您的需求(在纯 JavaScript 中哈哈):

<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
var a = 0;
function doIt() {
if(++a == 1) return;
alert('Thanks for the visit!');
}
</script>
</head>
<body>
<iframe name="iframe_a" onload="doIt()"></iframe>
<a href="http://www.example.com/" target="iframe_a">Go!</a>
</body>
</html>
于 2012-10-14T05:17:51.040 回答