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

前端开发:如何实现通知计数仅首次点击递减,避免重复触发

解决通知计数仅首次点击递减的问题

问题分析

原代码的核心问题:

  • 用array.pop()减少计数的逻辑错误,pop()只会移除数组最后一个元素,和当前点击的通知无关
  • 点击事件的判断逻辑颠倒,错误地在标记为clicked后才去减少计数,导致重复操作时仍会触发计数变更
  • 没有可靠的「未读」状态校验,无法区分首次点击和重复点击

修正方案

我们需要仅在通知处于未读状态时,点击才减少计数,同时标记该通知为已读,避免重复触发。

修正后的代码:

const noteItems = document.querySelectorAll("article");
const noteNumber = document.getElementById("notifs");

// 实时统计并更新未读通知数量
function updateNotificationCount() {
  const unreadCount = document.querySelectorAll("article.new").length;
  noteNumber.textContent = unreadCount;
}

document.addEventListener("DOMContentLoaded", function() {
  // 初始化未读样式与点击事件
  noteItems.forEach(item => {
    if (item.classList.contains("new")) {
      item.classList.add("new-item");
      item.setAttribute("notif-status", "new");
    }

    item.addEventListener("click", function() {
      // 仅当通知为未读状态时,触发计数减少
      if (this.classList.contains("new")) {
        this.classList.remove("new", "new-item");
        this.setAttribute("notif-status", "old");
        updateNotificationCount();
      }
      // 添加已读样式(可选)
      this.classList.add("read");
    });
  });

  // 设置初始计数
  updateNotificationCount();
});

关键改进点

  • 计数逻辑独立:用updateNotificationCount()实时统计未读通知数量,避免维护数组/变量时的同步错误
  • 状态校验准确:仅当通知带有new类(未读状态)时,点击才触发计数减少
  • 操作原子性:点击未读通知时,立即移除未读标记并更新计数,后续点击不会再触发计数变更
  • 代码更简洁:用forEach替代for循环,避免原代码中存在的闭包作用域问题

额外建议

  • 不要用disabled属性标记通知状态,它是表单元素的专属属性,语义上不合适,用自定义类名(如read)或data属性(如data-read="true")更合理
  • 如果需要批量标记已读,可以添加「标记全部已读」按钮,点击后移除所有通知的new类,再调用updateNotificationCount()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:05:56