2014-01-19 79 views
0

我有一個名爲find.html和文件result.html的文件。他們都加入這一行的頭:2個窗口需要全局變量

<script src="func.js"></script> 
在文件func.js

,第一行我寫

var reciever_username; 

現在,我有2個功能,在文件中「func.js 「

function sendMessage(username){ //called from find.html 
reciever_username = username; 
alert(reciever_username); //work good 
window.open('send_message.html', 'newwindow', 'width=300, height=250'); 

} 

function message_handle(){//called from result.html 
    alert(reciever_username); //show me : undefind 
    } 

我在做什麼錯?

+1

由於您沒有顯示* when/how *函數的調用方式,因此我只能假定在調用sendMessage之前調用message_handle。請注意,雖然每個窗口/選項卡都有自己的上下文,變量不會在它們之間共享。因此,如果您將兩個HTML文件加載到兩個不同的窗口/選項卡中,則每個都有自己的'reciever_username'變量。 –

+0

如果您想在Windows之間共享數據,則應該使用localStorage – Curious

回答

2

您的問題網頁窗口背景下,你有當你調用它會發生不同的窗口背景下的功能2個不同的頁面上下文,可以改爲嘗試這個辦法:

function sendMessage(username){ //called from find.html 
    localStorage.setItem("reciever_username",username); 
    alert(localStorage.getItem("reciever_username")); //work good 
    window.open('send_message.html', 'newwindow', 'width=300, height=250'); 

} 
function message_handle(){//called from result.html 
    alert(localStorage.getItem("reciever_username")); //show me : undefind 
} 

的localStorage的所有頁面之間共享你擁有相同的域名。

有關localStorage的更多信息,請轉至此link

1

導航到頁面的其他頁面上下文後將丟失。 因此,如果您的應用程序不是單頁應用程序,那麼您不能在兩個不同的頁面中使用全局變量。

相關問題