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

使用setInterval和事件未达预期:自动刷新时输入框数据被清空

解决自动刷新时输入框内容丢失的问题

问题根源

你通过$("#panel").load(...)刷新区域时,#panel内的所有DOM元素会被服务器返回的新内容替换,输入框作为其中的一部分,自然会被重置为空。另外原代码存在变量名大小写不一致的问题:myinterval(初始化时)和myInterval(清除时)拼写不同,导致焦点触发时无法正确停止定时器。

修复方案

刷新区域前先保存输入框的当前值,待刷新完成后再把值回填到新生成的输入框中,同时修正变量名的bug,移除重复的内联事件绑定。

修改后的完整代码

<td>
  <input id="numero" name="numero" type="text">
  <br>
</td>
// 统一变量名,避免大小写问题
let autoRefreshInterval = setInterval(refreshPanel, 3000);

const numeroInput = document.getElementById("numero");
numeroInput.addEventListener("focus", stopAutoRefresh);
numeroInput.addEventListener("blur", startAutoRefresh);

function refreshPanel() {
  // 刷新前保存输入框的值
  const inputValue = numeroInput.value;
  
  $("#panel").load(location.href + " #panel>*", function() {
    // 刷新完成后,找到新生成的输入框并恢复值
    document.getElementById("numero").value = inputValue;
  });
}

function stopAutoRefresh() {
  clearInterval(autoRefreshInterval);
}

function startAutoRefresh() {
  // 重新启动定时器前先清除旧的,避免重复创建
  clearInterval(autoRefreshInterval);
  autoRefreshInterval = setInterval(refreshPanel, 3000);
}

额外优化点

  • 移除了HTML中重复的onfocusin/onfocusout内联事件,避免和addEventListener绑定的逻辑冲突
  • 拆分了刷新逻辑为独立函数refreshPanel,代码更易维护
  • 启动定时器前先清除旧的,防止多次触发blur时创建多个定时器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:15:19