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

修复JavaScript实现用户名与评论添加至HTML无序列表的问题

解决方案

假设你的HTML结构如下(已有类似结构可直接复用):

<div class="comment-form">
  <input type="text" id="username" placeholder="输入用户名">
  <textarea id="comment" placeholder="输入评论内容"></textarea>
  <button id="submit-btn">提交评论</button>
</div>
<ul id="list"></ul>

对应的JavaScript代码可实现将用户名和评论同时添加到列表:

// 获取页面元素
const usernameInput = document.getElementById('username');
const commentInput = document.getElementById('comment');
const submitBtn = document.getElementById('submit-btn');
const commentList = document.getElementById('list');

// 监听提交按钮点击事件
submitBtn.addEventListener('click', function() {
  // 获取输入值并去除首尾空格
  const username = usernameInput.value.trim();
  const comment = commentInput.value.trim();

  // 验证输入不为空
  if (!username || !comment) {
    alert('请填写用户名和评论内容');
    return;
  }

  // 创建列表项元素
  const listItem = document.createElement('li');
  // 组合用户名和评论内容,可自定义样式结构
  listItem.innerHTML = `
    <strong>${username}</strong>:
    <span>${comment}</span>
  `;

  // 将列表项添加到无序列表中
  commentList.appendChild(listItem);

  // 清空输入框
  usernameInput.value = '';
  commentInput.value = '';
});

关键说明

  • 先获取输入框、按钮和列表的DOM元素,确保能正确访问目标节点
  • 点击提交时做简单非空验证,避免添加空评论
  • 创建<li>元素后,通过innerHTML将用户名(用<strong>强调)和评论内容组合成所需结构
  • 最后把新列表项追加到#list中,并清空输入框

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:22:04