You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

计算器计算错误显示异常及待办列表输入文本DOM监听问题求助

问题1:计算器计算出错时显示错误问题

解决思路及实现:

  • 用try-catch包裹计算逻辑,捕获除零、非法表达式等运算异常
  • 捕获异常时,将显示区域内容替换为*Error*提示
  • 监听用户输入操作,错误状态下开始新输入时自动清除错误提示

示例代码(假设计算器显示元素类名为.display):

const display = document.querySelector('.display');
const calculateBtn = document.querySelector('.calculate-btn');

calculateBtn.addEventListener('click', () => {
  try {
    const input = display.textContent;
    // 实际项目中建议用安全的表达式解析库替代eval,避免安全风险
    const result = eval(input);
    display.textContent = result;
  } catch (err) {
    display.textContent = 'Error';
  }
});

// 输入按键点击时清除错误状态
document.querySelectorAll('.input-key').forEach(key => {
  key.addEventListener('click', () => {
    if (display.textContent === 'Error') {
      display.textContent = '';
    }
    display.textContent += key.textContent;
  });
});
问题2:待办事项列表处理输入框文本内容

你的代码存在三个核心问题:固定待办内容、重复绑定清除事件、未处理空输入,修改方案如下:

  1. 获取输入框value作为待办内容
  2. 添加空值校验,避免创建空白待办
  3. 将清除事件移至外部,仅绑定一次,实现清空所有待办项的功能

修改后的代码:

const text = document.querySelector(".addinglist");
const button = document.querySelector(".add");
const bottom = document.querySelector(".bottom-part");
const clear = document.querySelector(".clear");

// 添加待办项逻辑
button.addEventListener("click", () => {
  const todoContent = text.value.trim();
  // 空内容直接返回,不创建待办
  if (!todoContent) return;

  const para = document.createElement("p");
  para.textContent = todoContent;
  bottom.append(para);
  // 添加后清空输入框
  text.value = '';
});

// 清空所有待办项,仅绑定一次事件
clear.addEventListener("click", () => {
  bottom.innerHTML = '';
});

内容的提问来源于stack exchange,提问作者deniz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 02:06:22