我設法讓代碼在條件滿足時使用函數更改按鈕的類。問題是我不想爲所有元素重複此操作,但在使用document.getElementById('buy'+gen)
而不是document.getElementById('buyhotdog')
時不起作用。我將在下面提供「工作代碼」和我嘗試工作的代碼。getElementById(「...」)。當試圖使用字符串+變量作爲編號時,className爲空
工作代碼:
function changeButtonHD() {
if (money < hotdog.cost) {
document.getElementById('buyhotdog').className = 'buttongrey';
}
else {
document.getElementById('buyhotdog').className = 'button';
}
}
,並與工作原理:changeButtonHD();
在與在window.onload激活間隔。
非工作代碼:
function changeButtonBC(gen) {
if (money < gen.cost) {
document.getElementById('buy'+gen).className = 'buttongrey';
}
else {
document.getElementById('buy'+gen).className = 'button';
}
}
我試圖讓它與changeButtonHD(hotdog);
你缺少引號'changeButtonHD(「熱狗」);' 。一方面只使用'hotdog'應該拋出一個錯誤,即'hotdog'沒有被定義,或者如果被定義了,那麼名爲'hotdog'的變量的內容很可能不是'hotdog'的值。 –
你確定'gen'是正確的使用方法嗎,因爲你既檢查'gen.cost',然後把_just_'gen'附加到''buy'''? –
簡單調試:'console.log('buy'+ gen)' - 這是什麼給你...? – deceze