0

将两个 onload 事件挂钩到 iframe 并在不同的 onload 尝试上发生的 javascript 代码是什么。

我希望第一个 onload 只做下一个 onload 重定向。这可能吗?

4

1 回答 1

1

New Answer

After re-reading your question, I realized you wanted the functions to to trigger on separate events. This is easier to achieve:

var ifr = document.getElementById('daiframe');

ifr.onload = function(){
    ifr.onload = function(){
        // do the redirect here
    };
};


ifr.src = 'http://initial.url/';

What is of utmost importance here is that you set the onload code above BEFORE the iframe gets the initial URL, like I did. Assuming you are writing the iframe HTML code directly, be sure that the SRC attribute points to about:blank.

Edit: From information given in comment and my earlier warning...

Let's say the PHP part looks like this:

$code = '<iframe src="http://some.url/"></iframe>';
echo $code;

That code needs to be changed to:

$code = '<iframe src="http://some.url/"></iframe>';
echo str_replace('<iframe ', '<iframe onload="ifrLoaded();" ', $code);

?><script type="text/javascript">
    var alreadyLoaded = false;
    function ifrLoaded(){
        if(alreadyLoaded){
            // do your redirect
        }else{
            alreadyLoaded = true;
        }
    }
</script>

Old Answer

Something like this?

function appendEvent(el, name, fn){
    if(typeof el[name] == 'function'){
        var oldfn = el[name];
        el[name] = function(){
            oldfn.apply(this, arguments);
            fn.apply(this, arguments);
        };
    }else{
        el[name] = fn;
    }
}


var ifr = document.getElementById('daiframe');

appendEvent(ifr, 'onload', function(){});
appendEvent(ifr, 'onload', function(){ /* do the redirect */ });

ifr.src = 'http://target.url/'; // since onload fires only after the URL is set

A working JSFiddle...

于 2012-09-19T20:15:15.560 回答