2015-02-11 67 views
0

我有兩個html文件,index.htmlgrade.html以及一個JavaScript文件myscript.js。當我點擊index.html中的按鈕時,我使用jquery getJSON加載一些文件。然後我想在grade.html中顯示數據並打開它。這是我的代碼:更改第二個html文件中的文本

指數:

<!DOCTYPE html> 
<html> 
<head> 
<title>Plz</title> 
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script> 
<script type="text/javascript" src="myscript.js"></script> 
</head> 

<body> 

<button id="btn" onclick="bcc()">Click me</button> 

</body> 

</html> 

等級:

<!DOCTYPE html> 
<html> 
<head> 
<title>Grades</title> 
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script> 
<script type="text/javascript" src="myscript.js"></script> 
</head> 

<body> 
<p id="para">hello</p> 
</body> 

</html> 

的MyScript:

var jsonDataToshow = null; 
function bcc(){ 

$.getJSON("https://dl.dropboxusercontent.com/u/12176084/data.json", function(data) { 
     jsonDataToshow = data;  
     //$('#para').text(data[0].firstName); 
     $('#para').text("good bye"); 
    }).fail(function(d, textStatus, error) { 
     console.error("getJSON failed, status: " + textStatus + ", error: "+error) 
}); 

window.location = "grade.html"; 
} 

所以我嘗試使用$('#para').text("good bye");和開放grade.html改變#para使用window.location = "grade.html";,但是當我打開grade.html #para打個招呼。我究竟做錯了什麼?

編輯: 我試圖創造index.html的兩個按鈕,一個改變的#para文本,並另開grade.html,但#para依然不改。爲什麼?我的猜測是,在加載grade.html頁面之前,我更改了#para的文本,並且重寫了它或其他內容。

EDIT2: 歐凱所以我想檢查是否javascritpt可以用

if ($("#para").length) { 
     alert("hello"); 
    } 

找到元素#para但我沒有找到它。我需要以某種方式加載grade.html文件嗎?

回答

0

您的位置:

  1. 發送請求
  2. 準備做一些事情(說「再見」)時,你得到的迴應
  3. 離開該頁面(以及它的JS執行環境)

由於您在得到回覆之前離開了該頁面,因此無論您準備如何處理它,都無法完成。

如果您希望在離開頁面之前等待響應,那麼您需要移動指令離開回調函數中的頁面。

+0

你的意思是我應該將「window.location =」grade.html「;」移動到$ .getJSON(「..:」,function(data){...}裏面,我試過但它沒有這是因爲我第一次將文本設置爲「再見」,並且當對grad.html進行更改時,我重新編碼了「hello」文本? – lijas 2015-02-11 17:28:38

+0

更多idead?什麼是標準方式更改第二個html-文件? – lijas 2015-02-12 14:49:35

相關問題