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

如何通过jQuery仅在MySQL新增评论时更新对应多个div?

解决MySQL新增评论时仅单个帖子div更新的问题

问题根源

你的代码核心问题是全局变量$i被所有帖子共享,导致所有帖子的更新判断都依赖同一个时间值。当某一个帖子的评论时间更新后,$i被替换为新时间,其他未更新的帖子的旧时间和这个新$i对比会触发错误的更新逻辑,最终导致非目标div内容异常。

解决方案

给每个帖子的div单独维护自己的最后评论时间,替代全局变量,让每个帖子的更新判断独立执行:

1. 修改HTML结构(使用标准data属性)

<div class="commcommmpost1" data-post-id="1" id="gantt1" data-last-comment-time="初始时间">comment from post with id 1</div>
<div class="commcommmpost1" data-post-id="2" id="gantt2" data-last-comment-time="初始时间">comment from post with id 2</div>
<div class="commcommmpost1" data-post-id="3" id="gantt3" data-last-comment-time="初始时间">comment from post with id 3</div>
<div class="commcommmpost1" data-post-id="4" id="gantt4" data-last-comment-time="初始时间">comment from post with id 4</div>
  • 用标准HTML5 data-post-id替代自定义idss属性,兼容性更好
  • 添加data-last-comment-time存储对应帖子的初始最新评论时间(页面渲染时从数据库获取填充)

2. 修改JavaScript逻辑

var auto_refresh = setInterval(function() {
    $('.commcommmpost1').each(function() {
        var $this = $(this);
        var postId = $this.data('post-id');
        var lastTime = $this.data('last-comment-time');

        $.get("bed2.php?id=" + postId, function(newTime) {
            // 仅当前帖子的评论时间变化时才更新
            if (newTime !== lastTime) {
                $('#gantt' + postId).load('bed1.php?id=' + postId, function() {
                    // 更新当前div存储的最新时间,确保下次判断准确
                    $this.data('last-comment-time', newTime);
                }).fadeIn("slow");
            }
        });
    });
}, 2000);

额外注意事项

  • 确保bed2.php逻辑正确:接收id参数后,返回对应帖子的最新评论时间戳/格式化时间,且前后端时间格式保持一致
  • 页面首次渲染时,data-last-comment-time的初始值必须和bed2.php返回的初始时间完全匹配,避免首次加载就触发不必要的更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:51:15