点击数字按钮后num-area文本转数组始终为空的技术问询
问题:点击按钮输入内容后,pre元素文本转数组始终为空
我想实现点击数字按钮时,把数字写入id为num-area的<pre>元素,之后将该元素的文本内容转成数组。但就算输入了数字,把pre元素的textContent转成数组后,值始终是空的(长度为0)。相关代码如下:
原代码
HTML
<pre id="num-area"></pre> <pre id="result"></pre> <span id="one">1</span> <span id="two">2</span> <span id="plus">+</span> <span id="equal">=</span>
CSS
#num-area { width: 440px; height: 100px; position: absolute; top: 0; font-family: Arial; font-size: 35px; background-color: #ddd; color: #000; padding:20px; } #result { width: 440px; height: 50px; position: absolute; top: 150px; font-family: Arial; font-size: 20px; background-color: #fdd; color: #000; } span { bottom: 0; position: absolute; width: 90px; height: 55px; background-color: blue; border-radius: 15px; color: #fff; font-size: 20px; font-family: Arial; display: flex; justify-content: center; align-items: center; cursor: pointer; } #one { margin-left: 100px; } #plus { margin-left: 200px; } #equal { margin-left: 300px; }
JavaScript
const typedNum = document.querySelector("#num-area"); const result = document.querySelector("#result"); const one = document.querySelector("#one"); const two = document.querySelector("#two"); const plus = document.querySelector("#plus"); const equal = document.querySelector("#equal"); const arr_equation = typedNum.textContent.split(""); one.addEventListener("click", function () { typedNum.textContent += "1"; }) two.addEventListener("click", function () { typedNum.textContent += "2"; }) plus.addEventListener("click", function () { typedNum.textContent += " + "; }) equal.addEventListener("click", function () { result.textContent = arr_equation; })
问题原因
arr_equation是在页面加载完成时就赋值的,此时num-area的文本内容为空,所以拆分后得到的是空数组。后续点击按钮修改num-area的文本时,arr_equation不会自动更新,始终保持最初的空数组状态。
解决方案
将arr_equation的定义和赋值逻辑移到equal按钮的点击事件中,每次点击等号时实时获取num-area的最新文本内容并拆分:
修正后的JavaScript代码
const typedNum = document.querySelector("#num-area"); const result = document.querySelector("#result"); const one = document.querySelector("#one"); const two = document.querySelector("#two"); const plus = document.querySelector("#plus"); const equal = document.querySelector("#equal"); one.addEventListener("click", function () { typedNum.textContent += "1"; }) two.addEventListener("click", function () { typedNum.textContent += "2"; }) plus.addEventListener("click", function () { typedNum.textContent += " + "; }) equal.addEventListener("click", function () { // 实时获取当前文本并转换为数组 const arr_equation = typedNum.textContent.split(""); result.textContent = arr_equation; })
这样每次点击等号时,都会读取num-area的最新内容,拆分后得到正确的数组并显示在result中。
内容的提问来源于stack exchange,提问作者BLACK SHADOW-TG
相关产品推荐
相关产品推荐

