谁能解释为什么currentOperationScreen没有显示/被分配5?Console.log显示number = 5.
谢谢!
let currentOperationScreen = document.getElementById('currentOperationScreen');
currentOperationScreen = '';
console.log(currentOperationScreen);
function appendToDisplay(numbr) {
console.log(numbr);
console.log(currentOperationScreen);
if (numbr === '0' && currentOperationScreen.textContent === '') {
return;
}
currentOperationScreen.textContent += numbr;
console.log(currentOperationScreen);
}
dataButton = document.querySelectorAll('.data-number');
dataButton.forEach((button) =>
button.addEventListener('click', () => appendToDisplay(button.textContent)))
javascript有自动转换。,它可以比较字符串和数字。使用===而不是==。如果你想使用===初始化currentOperationScreen为0而不是'0'更多详细信息在这里MDN自动转换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.tailwindcss.com"></script>
<title>Document</title>
</head>
<body>
<div id="currentOperationScreen bg-green-400"></div>
<button class="data-number px-5 py-3 bg-green-400 rounded"> click </button>
<button class="data-number px-5 py-3 bg-green-400 rounded"> click </button>
<button class="data-number px-5 py-3 bg-green-400 rounded"> click </button>
<script>
let currentOperationScreen = document.getElementById('currentOperationScreen');
currentOperationScreen = 0;
function appendToDisplay(numbr) {
if (numbr === 0 && currentOperationScreen === 0) {
return;
}
currentOperationScreen += numbr;
console.log(currentOperationScreen);
}
dataButton = document.querySelectorAll('.data-number');
dataButton.forEach((button) =>
// add number to function appendToDisplay
button.addEventListener('click', () => appendToDisplay(5)))
</script>
</body>
</html>
的代码结果如下
你是这个意思吗?