仅在锚点onclick之后iframe onload事件

时间:2012-10-14 04:16:18

标签: javascript html iframe

示例代码:

<!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 个答案:

答案 0 :(得分:0)

当它在DOM中时,没有(理智的)方法来阻止iframe的加载。在加载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>

答案 1 :(得分: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>

答案 2 :(得分: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>

答案 3 :(得分:0)

这个很有趣,但它可以满足你的需求(纯粹的JavaScript lol):

<!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>