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

JQuery城市时间查询:更换城市后时间波动及表单重置问题求助

问题解决:连续查询城市时间波动+表单重置方案

1. 时间波动的核心原因

每次点击.searchbutton时,你都调用了setInterval,但没有清除之前的定时器。这就导致多个定时器同时运行,各自用不同的diff值计算小时,页面上的小时元素被多个定时器交替修改,所以会在新旧城市时间之间波动。

2. 修复代码步骤

步骤1:声明全局变量存储定时器ID

在函数外部定义变量保存定时器ID,方便后续清除旧定时器:

// 全局存储定时器ID,初始值为null
let timeInterval = null;

步骤2:每次搜索前清除旧定时器

在点击事件开头,先检查并清除正在运行的旧定时器,再启动新的:

$(document).on("click", ".searchbutton", function(e){
    e.preventDefault();
    var city = $("#searchbar").val();
    
    // 清除之前的定时器,避免多个定时器同时运行
    if(timeInterval !== null){
        clearInterval(timeInterval);
    }
    
    // 补充:这里需要根据city获取对应经度Long的逻辑(你代码中Long变量未定义)
    // 示例:var Long = getCityLongitude(city);
    
    // 启动新定时器并保存ID
    timeInterval = setInterval(function(){
        var hdate = new Date()
        var offset = 0 - hdate.getTimezoneOffset()/60
        var hmin = hdate.getMinutes()
        var hsec = hdate.getSeconds()
        var diff = Math.round(Long/15) - offset
        
        let disphour;
        if((hdate.getHours() + diff) > 23){
          disphour = (hdate.getHours() + diff) - 24
        }
        else if((hdate.getHours() + diff) < 0){
          disphour = 24 + (hdate.getHours() + diff)
        }
        else{
          disphour = hdate.getHours() + diff
        }
        var formattedNumberh = ("0" + disphour).slice(-2)
        $("#hour").text(formattedNumberh)
        
        var formattedNumberm = ("0" + hmin).slice(-2)
        var formattedNumbers = ("0" + hsec).slice(-2)
        $("#minute").text(formattedNumberm)                                    
        $("#second").text(formattedNumbers)                                          
    }, 1000)   
})

步骤3:表单输入完全重置

如果需要清空表单旧值,有两种常用方式:

  • 搜索后自动清空输入框:
    在获取city值后添加:
    $("#searchbar").val("");
    
  • 添加独立重置按钮:
    先添加HTML按钮:
    <button class="resetbutton">重置</button>
    
    再绑定重置逻辑:
    $(document).on("click", ".resetbutton", function(e){
        e.preventDefault();
        $("#searchbar").val("");
        // 可选:停止时间显示并清空
        if(timeInterval !== null){
            clearInterval(timeInterval);
            timeInterval = null;
            $("#hour").text("00");
            $("#minute").text("00");
            $("#second").text("00");
        }
    })
    

3. 额外注意事项

  • 你代码中的Long变量未定义,必须补充根据城市名称获取对应经度的逻辑,否则diff计算会报错。
  • 事件参数建议用e而非event,避免严格模式下出现未定义错误。
  • 变量disphour用let声明,避免变成全局变量引发其他问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:20:35