You need to enable JavaScript to run this app. 如何创建可动态添加到列表的评论表单,自动生成连续ID存入数组
优惠活动
大模型
产品
解决方案
定价
更多

如何创建可动态添加到列表的评论表单,自动生成连续ID存入数组

功能实现修改方案

需要调整的核心问题

  • DOM选择错误:评论列表<ul>不在表单内部,原代码通过commentForm.querySelector无法获取到该元素
  • 表单默认行为未阻止:点击表单内的按钮会触发页面提交刷新,导致新增的评论丢失
  • 数组操作逻辑错误:map是遍历数组返回新数组的方法,不能用于向原数组新增元素,应该使用push方法
  • 变量使用错误:nextId++外层包裹了引号会变成字符串,不符合id为数字类型的要求
  • 元素创建逻辑错误:createElement直接读取数组的id和text属性,而comments是数组不是对象,无法读取到对应值

修改后完整JS代码

let nextId = 1;
const comments = [];

const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
// 修正评论列表获取逻辑
const commentList = document.querySelector('[data-id="comment-list"]');

button.addEventListener('click', (e) => {
  // 阻止表单默认提交刷新页面
  e.preventDefault();
  const inputText = commentInput.value.trim();
  if (inputText !== '') {
    // 构造符合要求的评论对象
    const newComment = {
      id: nextId++,
      text: inputText
    };
    // 新增到存储数组
    comments.push(newComment);
    // 传入对象创建DOM元素
    createElement(newComment);
    // 清空输入框方便下次输入
    commentInput.value = '';
  }
});

function createElement(comment) {
  const newCommentEl = document.createElement('li');
  newCommentEl.setAttribute('data-comment-id', comment.id);
  newCommentEl.textContent = comment.text;
  // 追加到列表末尾,符合最新评论在最底部的要求
  commentList.appendChild(newCommentEl);
}

效果验证

页面初始加载时comments数组为空,每次点击Add按钮仅当输入框有有效内容时才会新增评论,id会连续递增,最新评论默认追加到列表最底部,完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 10:45:04