문제

Looked through the questions and there are few similar ones on the subject of "ReferenceError foo is not defined". However, I'm not able to detect the error in my code and get it working. It works fine in Chrome and Safari, but not in IE, Opera and Firefox:

The code in the HTML

<a href="javascript:foo(1)" target="_parent">

calls a javascript placed in the header as

<script type="text/javascript" src="http://www.site.com/include/script.js"></script>

which is defined as the following:

function foo(language){
    url = window.parent.location.href;
    parts = url.split('/');
    page = parts[3];

    newUrl = "";

    if (language == 1){
        newUrl = "http://www.site1.com/" + page;
    } else if (language == 2){
        newUrl = "http://www.site2.com/" + page;
    } else{
        newUrl = "http://www.site3.com/" + page;
    }

    window.parent.window.location.href = newUrl;
}

Reading the related questions I tested to change to window.foo = function(language){...}, but it didn't help.

Seems straight forward and as simple as it gets, but of some reason foo is undefined in IE and firefox.

Should be added that the javascript is in the "top.html" which is an embeded iframe for each page. Somehow chrome manages this while IE doesn't (but the script works if I browse to http://www.site1.com/top.html and click on the button calling redirect(language);)

도움이 되었습니까?

해결책

Your problem is that the link is targeted (has a target="_parent" bit).

This means that it runs in the scope of the target window, not in the window it's in. And there is no function named foo there.

다른 팁

It look like your link is in a "iframe" tag, but the foo function is defined in top-level window object's scope.

There a two ways to fix this:

You should use window.partent to reference the top-level window object, try to change the link to

<a href="javascript:window.partent.foo(1)" target="_parent">

Or, move the function code to the same html file's head tag as the link.

By the way, you should use var keyword to declare variables.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top