我的目標是有一個按鈕,onclick將調用一個函數,以改變html標籤的樣式和按鈕本身的文本(或innerHTML)。不應該那麼辛苦吧?嗯......Javascript無法設置按鈕id的innerHTML,因爲它是「空」
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>New look for my site!</title>
<link rel="stylesheet" type="text/css" href="main.css">
<script src="change-template.js"></script>
</head>
<body>
<aside>
<button type="button" id="template-button" onclick="changeTemplate()">Nightmode: On</button>
</aside>
<main>
<h1>New page look for my site</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</main>
</body>
</html>
CSS(main.css的):
html{
background: "#111";
color: "#0F0";
}
JS(變化template.js):
var html = document.getElementsByTagName('html')[0];
var button = document.getElementById('template-button');
var nightmode = true;
function changeTemplate(){
//change to lighter color if black and vice versa
if(nightmode){
html.style.background = "#EEE";
html.style.color = "#000";
button.innerHTML = "Nightmode: OFF";
}else{
html.style.background = "#111";
html.style.color = "#0F0";
button.innerHTML = "Nightmode: ON";
}
nightmode = !nightmode;
}
而且我m得到這個錯誤
Uncaught TypeError: Cannot set property 'innerHTML' of null at changeTemplate (change-template.js:10) at HTMLButtonElement.onclick (new-look.html:11)
所以,請幫助我,它是90度,我坐在這裏的飢餓邊緣,強調這個簡單的問題,幾乎沒有想到。
先生/女士,你讓我免於瘋狂。我覺得自己忘記了這一點。這就像在javascript中的function functionName(){}',它甚至可以在定義之前調用,但'var function = function(){}'不能。所以我不習慣這個命令。我現在要去吃飯了。 – TheCaliCoder