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

表单提交消息无法显示至chat_container容器的问题求助

问题排查与修复方案

1. HTML结构错误

你的HTML中<button>标签未闭合,会导致DOM解析异常,直接影响表单的正常提交逻辑:
原错误代码:

<button type="submit">
  <img src="./send.svg" alt="send" />

修复后:

<button type="submit">
  <img src="./send.svg" alt="send" />
</button>

2. 缺失关键函数chatStripe的实现

你的JS代码调用了chatStripe()来生成聊天消息的HTML结构,但没有提供这个函数的定义——这是消息无法显示的核心原因,没有它就无法把输入的文本转化为可渲染的DOM元素。

你需要补充类似这样的chatStripe实现(示例结构,可根据你的样式需求调整):

function chatStripe(isBot, message, id) {
  return `
    <div class="chat-item ${isBot ? 'bot-message' : 'user-message'}" ${id ? `id="${id}"` : ''}>
      <p>${message}</p>
    </div>
  `;
}

3. handleSubmit函数存在的问题

  • 函数未完成:你声明了async函数,但最后一行获取messageDiv后没有后续逻辑,这会影响机器人回复的后续处理(如果有的话)。
  • DOM操作优化:使用innerHTML +=会触发DOM重绘,可能导致之前绑定的事件丢失,建议改用insertAdjacentHTML:
const handleSubmit = async(e) => {
  e.preventDefault();
  const data = new FormData(form);
  const userMessage = data.get('prompt');
  
  // 替换innerHTML +=为insertAdjacentHTML,避免DOM重绘问题
  chatContainer.insertAdjacentHTML('beforeend', chatStripe(false, userMessage));
  form.reset();
  
  const uniqueId = generateUniqueId();
  chatContainer.insertAdjacentHTML('beforeend', chatStripe(true, " ", uniqueId));
  chatContainer.scrollTop = chatContainer.scrollHeight;
  
  const messageDiv = document.getElementById(uniqueId);
  // 此处补充机器人回复的逻辑,比如调用接口、更新messageDiv内容等
};

4. 冗余的回车事件监听

表单默认会在按下回车键时触发submit事件,你额外绑定的keyup事件会导致handleSubmit被重复调用,建议直接移除这段冗余代码:

// 删除以下代码
form.addEventListener('keyup', (e) => {
  if (e.keyCode === 13) {
    handleSubmit(e);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:42:29