我剛開始學習JS,我對它的理解不是很好。我一般不擅長編碼,所以為這個真正準系統而且很可能是錯誤的網站道歉,但我現在想要完成的只是在按下按鈕時更改網站的背景顏色。當我在 <script< 中執行此操作時,它起作用了,但是當我將它移到單獨的 JS 檔案中時,它停止了作業。我收到的錯誤訊息是:SyntaxError: Unexpected token '}'。期望在函式體的開頭有一個開頭的“{”。有人可以幫忙嗎?先感謝您!
function makeRed() {
document.getElementById('temp').style.backgroundColor = 'lightsalmon';
}
let btnRed = document.getElementById = ('btnRed');
btnRed.addEventListener("click", makeRed);
body {
background-color: lightyellow;
text-align: center;
padding: 0;
margin: 0;
}
.temperature {
color: darkgoldenrod;
font-family: Optima, sans-serif;
}
input {
border: none;
border-bottom: 2px solid darkgoldenrod;
background-color: lightyellow;
width: 50px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
#header {
background: darkgoldenrod;
font-size: 20px;
color: lightyellow;
font-family: Optima, sans-serif;
}
<html>
<head>
<title>Sun tester</title>
<link rel="stylesheet" href="stylesheet.css">
<link rel="icon" href="https://external-content.duckduckgo.com/iu/?u=http://cdn.onlinewebfonts.com/svg/img_40038.png&f=1&nofb=1" type="image/x-icon">
</head>
<body>
<div id="header">
<h1 id="h1">Sun Tester</h1>
</div>
<div class="temperature">
<p id="temp2">Temperature:
<input type="number" id="temp"> °C</p>
</div>
<button type="button" id="btn-Red">Click Me!</button>
<script src="script.js"></script>
</body>
</html>
uj5u.com熱心網友回復:
您正在將方法btnRed和document.getElementById方法都分配給 String 值'btnRed',而不是實際運行該getElementById方法并將其傳遞給一個引數"btnRed"
所以只需更改
let btnRed = document.getElementById = ('btnRed');為
let btnRed = document.getElementById('btnRed');
uj5u.com熱心網友回復:
您需要將 HTML 元素更改btn-Red為btnRed并修復您的 JavaScript……試試這個。
function makeRed() {
let r = document.getElementById('temp')
r.style.backgroundColor = 'lightsalmon';
}
let btnRed = document.getElementById('btnRed');
btnRed.addEventListener("click", makeRed);
body {
background-color: lightyellow;
text-align: center;
padding: 0;
margin: 0;
}
.temperature {
color: darkgoldenrod;
font-family: Optima, sans-serif;
}
input {
border: none;
border-bottom: 2px solid darkgoldenrod;
background-color: lightyellow;
width: 50px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
#header {
background: darkgoldenrod;
font-size: 20px;
color: lightyellow;
font-family: Optima, sans-serif;
}
<html>
<head>
<title>Sun tester</title>
<link rel="stylesheet" href="stylesheet.css">
<link rel="icon" href="https://external-content.duckduckgo.com/iu/?u=http://cdn.onlinewebfonts.com/svg/img_40038.png&f=1&nofb=1" type="image/x-icon">
</head>
<body>
<div id="header">
<h1 id="h1">Sun Tester</h1>
</div>
<div class="temperature">
<p id="temp2">Temperature:
<input type="number" id="temp"> °C</p>
</div>
<button type="button" id="btnRed">Click Me!</button>
<script src="script.js"></script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465475.html
標籤:javascript
