我試圖學習 javascript 以撰寫網站,我已經知道 html 和 css 并考慮制作一個簡單的邏輯門,但是一旦我構建了它,我就無法讓它作業。這是帶有以下腳本的 html 檔案。
<!DOCTYPE html>
<html>
<body>
<p id="logic">xor: 0 or: 0 and: 0</p>
<button onclick="thisScript()">script</button>
<script>
let A = 1
let B = 1
function thisScript() {
if ((A == 1 || B == 1)&& !(A == 1 && B == 1)) {
let xor = 1
} else {
let xor = 0
}
if (A == 1 || B == 1) {
let or = 1
} else {
let or = 0
};
if (A == 1 && B == 1) {
let and = 1
} else {
let and = 0
};
document.getElementById("logic").innerHTML = `xor: ${xor} or: ${or} and: ${and}`
};
</script>
</body>
</html>
我嘗試在每個 if/else 陳述句中移動 dom,但它仍然不起作用它仍然說變數 xor 未定義
uj5u.com熱心網友回復:
這只是一個變數作用域問題,您的變數被限定在if陳述句的范圍內,這意味著它們不能被函式中的最后一行代碼訪問。下面的代碼片段使變數成為全域變數,但將它們范圍限定為函式也有效(第二個代碼片段)。查看此網頁以獲取有關 JS 范圍的更多資訊。
let A = 1
let B = 1
let xor, and, or;
function thisScript() {
if ((A == 1 || B == 1) && !(A == 1 && B == 1)) {
xor = 1
} else {
xor = 0
}
if (A == 1 || B == 1) {
or = 1
} else {
or = 0
};
if (A == 1 && B == 1) {
and = 1
} else {
and = 0
};
document.getElementById("logic").innerHTML = `xor: ${xor} or: ${or} and: ${and}`
};
<!DOCTYPE html>
<html>
<body>
<p id="logic">xor: 0 or: 0 and: 0</p>
<button onclick="thisScript()">script</button>
</body>
</html>
let A = 1
let B = 1
function thisScript() {
let xor, and, or;
if ((A == 1 || B == 1) && !(A == 1 && B == 1)) {
xor = 1
} else {
xor = 0
}
if (A == 1 || B == 1) {
or = 1
} else {
or = 0
};
if (A == 1 && B == 1) {
and = 1
} else {
and = 0
};
document.getElementById("logic").innerHTML = `xor: ${xor} or: ${or} and: ${and}`
};
<!DOCTYPE html>
<html>
<body>
<p id="logic">xor: 0 or: 0 and: 0</p>
<button onclick="thisScript()">script</button>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/351811.html
標籤:javascript html dom 逻辑
