【发布时间】:2021-07-13 13:29:42
【问题描述】:
我是编码新手,参加过几次训练营,现在尝试用 javascript 制作计算器。 当我在单击 = 时尝试评估 2 个值时会出现问题。请老师指导我。 我尝试了一些解决方法,但它们没有工作,观看了一些 youtube 视频,但感觉就像我在我的项目中复制粘贴了一些其他代码,所以为了改进我需要自己做一些事情,或者至少知道问题出在哪里。
var buttons = document.querySelectorAll('button')
var result = document.getElementById('screen')
function number() {
for (num of buttons) {
num.addEventListener('click', (e) => {
buttonText = e.target.innerText
console.log(buttonText)
result.value += buttonText
if (buttonText === '=') {
result.value = eval('result.value')
} else if (buttonText === 'x') {
buttonText = '*'
} else if (buttonText === 'C') {
result.value = ''
}
})
}
}
number()
body {
font-family: 'sans-serif', Tahoma, Geneva, Verdana;
}
.container {
text-align: center;
}
input {
font-size: 1.3rem;
margin-bottom: .5rem;
padding: .2rem;
text-align: right;
}
input:focus {
border: none;
}
table {
margin: auto;
}
button {
width: 3.38rem;
height: 2rem;
border: none;
font-size: 16px;
cursor: pointer;
background-color: aliceblue;
}
button:hover {
background-color: #d4c2c2;
}
td:hover {
background-color: #d4c2c2;
}
<!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" />
<title>Calculator</title>
<link rel="stylesheet" href="style.css" />
<script src="https://kit.fontawesome.com/c77dc29510.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h1>Calculator</h1>
<input type="text" value="" id="screen" />
<table>
<tr>
<td colspan="2" style="background-color: aliceblue;"><button> <i class="fas fa-backspace"</i> </button></td>
<td><button>C</button></td>
<td><button>%</button></td>
</tr>
<tr>
<td><button>7</button></td>
<td><button>8</button></td>
<td><button>9</button></td>
<td><button>x</button></td>
</tr>
<tr>
<td><button>4</button></td>
<td><button>5</button></td>
<td><button>6</button></td>
<td><button>-</button></td>
</tr>
<tr>
<td><button>1</button></td>
<td><button>2</button></td>
<td><button>3</button></td>
<td><button>+</button></td>
</tr>
<td><button>0</button></td>
<td><button>.</button></td>
<td><button>/</button></td>
<td><button>=</button></td>
</table>
</div>
</body>
<script src="calculator.js"></script>
</html>
【问题讨论】:
-
可能你的意思是
eval(result.value)来评估字符串的内容! -
你为什么要这样做?这只会将属性设置为已经存在的值。
-
您正在尝试评估实际字符串:
result.value = eval('result.value')。您需要删除变量周围的引号。 (也可以使用带有代码高亮功能的编辑器,并始终检查编辑器如何为您的代码部分着色) -
您的代码正在评估
'result.value',然后返回result元素的值。正如 phuzi 所说,您需要评估值中的字符串,即result.value,
标签: javascript html css eval calculator