2016-12-07 50 views
-1

我有一個帶有多個按鈕的頁面,每個按鈕都與打開新窗口的加載函數綁定,然後將其設置爲在頁面加載後單擊哪個按鈕。 我一直在對象中存儲選項,正在使用的選項在currentTile之下。但是,一旦加載頁面,出現的文字就是undefined,但是我沒有在load()中定義currentTile爲什麼屬性在函數中定義時未定義?

function tile(question, answer, points) { 
    this.question = question; 
    this.answer = answer; 
    this.points = points; 
} 

var currentTile = {}; 

var testTile = new tile("How are you?", "Fine", 200); 

function load(tile) { 
    currentTile = tile; 
    window.open("question.html", "_self"); 
} 

function setText() { 
    document.getElementById("qSlot").innerHTML = currentTile.question; 
    document.getElementById("value").innerHTML = "" + currentTile.points + ""; 
} 

load()被稱爲像這樣的HTML:提前 <td onclick="load(testTile)"></td>

感謝。

+2

你在哪裏調用加載函數? – Geeky

+3

您正在將傳遞給'load'('tile')的值分配給'currentTile',但您並未顯示如何調用'load'。可推測你沒有傳遞任何價值的功能。 –

+0

我在html代碼中調用它,''td onclick =「load(testTile)」>' –

回答

1

您正在使用window.open("question.html", "_self");這與重新加載頁面一樣好(假設您的當前頁面爲question.html)。所以當頁面重新加載時,你的JS代碼會重新執行,包括語句var currentTile = {};。這就是爲什麼你得到undefinedcurrentTile.questioncurrentTile.points

不直接調用window.open("question.html", "_self");直接調用setText(),它會正確顯示文本。 (你在哪裏打電話setText()?)。