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

<input type="number">点击取消后再次打开消失的原因与修复方案

问题原因及修复方案:日期选择元素点击取消后消失

核心问题原因

  1. 日期元素消失的直接原因
    取消按钮的点击事件中执行了 date.textContent = "",这行代码会彻底清空#date-detail容器内的所有子元素(包括里面的<label>和<input>)。因为textContent属性会替换掉元素的所有子节点,而非仅修改文本内容,第一次点击取消后这些输入框就被删除,再次打开自然无法显示。

  2. e.preventDefault()无效的原因
    cancel是普通按钮,既不是表单提交按钮,也没有触发页面导航等默认行为,调用e.preventDefault()没有实际作用,属于冗余代码。

修复步骤

1. 替换错误的清空逻辑

删除date.textContent = ""这行代码,保留后续对日期输入框的重置逻辑即可(原本就存在重置年/月/日输入框值的代码)。

2. 移除无用的e.preventDefault()

直接删掉这行冗余代码,不影响功能逻辑。

3. 修复HTML语法错误(可选但建议)

原HTML中存在标签未正确闭合的问题,可能引发潜在渲染异常:

  • <input type="number" id="day" name="day"></input 改为 <input type="number" id="day" name="day">(input为自闭合标签,无需</input>)
  • <textarea id="diaryContent"></textarea 改为 <textarea id="diaryContent"></textarea>

修改后的完整JS代码示例

function showDiaryDetail(isNew, original_tag, original_mood, original_date, original_description) {
  newDiaryTemplate.style.display = "block";
  const tag = document.querySelector("#tag-detail");
  const mood = document.querySelector("#mood-detail");
  const date = document.querySelector("#date-detail");
  const year = document.querySelector(`input[name="year"]`);
  const month = document.querySelector(`input[name="month"]`);
  const day = document.querySelector(`input[name="day"]`);
  const content = document.querySelector("#diaryContent");
  const img = document.querySelector("#diaryPicture");
  const save = document.querySelector("#saveDiary1");
  const cancel = document.querySelector("#cancel");
  let week;

  if (isNew === true) {
    let time = new Date();
    year.value = time.getFullYear();
    month.value = time.getMonth() + 1;
    day.value = time.getDate();
    week = time.getDay();
  }

  if (!cancelCreate) {
    cancelCreate = true;
    cancel.addEventListener("click", () => {
      newDiaryTemplate.style.display = "none";
      tag.value = "";
      mood.value = "";
      // 重置日期输入框值,而非清空容器
      year.value = new Date().getFullYear();
      month.value = new Date().getMonth() + 1;
      day.value = new Date().getDate();
      content.value = "";
    });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:35:53