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

为何appendChild未从数组追加通知反而替换?技术求助

问题:随机通知无法追加,仅替换旧元素

点击按钮时想显示随机通知,让通知在列表中留存一段时间并展示所有出现过的通知。但当前代码新通知会替换旧通知,而非追加到列表中;仅使用单条通知文本时功能正常。

问题原因

你只在全局创建了一个notif DOM元素,每次点击按钮只是修改这个元素的文本内容,然后重复执行appendChild和remove操作。由于DOM中同一个元素不能同时存在多个实例,所以每次操作都是把这个唯一的元素重新添加到容器里(相当于移动/替换),而非创建新的通知项。

修正代码

HTML(无需修改)

<div>
    <button class="btn toast_btn darkmode" id="toast_btn">Click me please</button>
    <div id="container"></div>
</div>

JavaScript(核心修改:每次点击创建新元素)

const toastBtn = document.getElementById('toast_btn');
const container = document.getElementById('container');

const myArray = [
    { notification: "1" },
    { notification: "2" },
    { notification: "3" },
    { notification: "4" },
    { notification: "5" },
    { notification: "6" },
    { notification: "7" },
    { notification: "8" }
];

toastBtn.addEventListener('click', () => {
    createNotification();
})

function createNotification() {
    // 每次点击都创建新的通知元素
    const notif = document.createElement('div');
    notif.classList.add('toast');

    let random = Math.floor(Math.random() * myArray.length);
    notif.innerText = myArray[random].notification;

    container.appendChild(notif);

    setTimeout(() => {
        notif.remove();
    }, 3000);
};

说明

  • 将notif元素的创建逻辑移到createNotification函数内部,确保每次点击都生成全新的DOM元素
  • 每个新生成的通知元素会独立添加到容器中,3秒后自动移除,实现"追加展示所有通知"的效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:35:35