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

点击评论区回复按钮仅在第一条评论下新增表单如何解决

问题原因

你当前代码里使用document.getElementsByClassName('formbox')[0]只会匹配页面中第一个类名为formbox的元素,所以不管点击哪个回复按钮,表单都会插入到第一条评论的容器里。


修改方案

  1. 修改HTML的点击事件,把当前点击的按钮实例作为参数传入函数
  2. 调整JS逻辑,根据传入的按钮找到对应评论的formbox容器,再插入表单

修改后代码

HTML部分(每条评论的按钮和容器都按这个结构写即可):

<button onclick="addtextbox(this)">reply</button>
<div class="formbox"></div>

JavaScript部分:

function addtextbox(btn) {
  // 找到当前按钮对应的formbox容器
  const targetBox = btn.nextElementSibling;
  // 可选:避免重复生成表单,已经存在就直接返回
  if (targetBox.querySelector('form')) return;

  // Create a form dynamically.
  var form = document.createElement("form");
  
  form.setAttribute("method", "post");
  form.setAttribute("action", "submit.php");

  // Create an input element for replyText.
  var replyInput = document.createElement("input");
  
  replyInput.setAttribute("type", "text");
  replyInput.setAttribute("name", "body");
  replyInput.setAttribute("placeholder", "Your Comment");
  form.append(replyInput);
  
  // 把表单插入到当前评论的容器中,而非全局第一个容器
  targetBox.appendChild(form);
}

补充说明

如果你的评论DOM结构里按钮和formbox不是直接相邻的兄弟元素,可以把btn.nextElementSibling替换为btn.parentElement.querySelector('.formbox'),只要保证能匹配到当前评论范围内的formbox即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:24:01