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

点击Add Chapter按钮未触发Submit却导致表单自动提交跳转求助

解决点击"Add Chapter"按钮意外提交表单的问题

我一眼就揪出问题根源了——你的"Add Chapter"按钮放在<form>标签内部,但没有明确指定type="button",浏览器会默认把它识别为type="submit"类型按钮。这就导致每次点击它时,浏览器不仅会执行spawnSilly()函数,还会自动触发表单提交,直接跳转到title-processing.php页面,这就是你看到的跳转现象。

第一步:修复表单提交问题

只需要给"Add Chapter"按钮加上type="button"属性,就能阻止它触发表单提交:

<button id="spawnbtn" type="button" onClick="spawnSilly();">Add Chapter</button>

这样点击它就只会执行你写的spawnSilly()函数,不会再跳转到处理页面了。

第二步:修正JS代码里的ID设置错误

顺便提一句,你设置元素ID的方式是错误的,比如这行代码:

input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")

这会把字符串"var timestamp = new Date().getUTCMilliseconds();"直接当成ID值,而不是执行代码生成时间戳。正确的写法应该是先计算时间戳,再赋值给ID:

var timestamp = new Date().getUTCMilliseconds();
input.setAttribute("id", "chapterInput_" + timestamp);

同理,button、div、删除按钮的ID设置也需要改成这种方式,否则后续通过ID操作元素时会出问题。

修正后的完整JS函数示例

我还优化了子元素数量的获取逻辑,让代码更清晰:

function spawnSilly() {
  // 生成唯一时间戳用于ID
  var timestamp = new Date().getUTCMilliseconds();
  var div = document.createElement("LI"); 
  var input = document.createElement("INPUT");
  var button = document.createElement("BUTTON");
  var del_button = document.createElement("BUTTON")

  // 获取当前列表已有子元素数量,用于生成唯一name和章节编号
  var currentChapterCount = $('#spawnList').children().length;
  var newChapterNumber = currentChapterCount + 1;
  var stringNumber = String(newChapterNumber);

  input.setAttribute("type", "text");
  input.setAttribute("name", "chapterInput" + stringNumber);
  input.setAttribute("placeholder", "Title");
  input.setAttribute("id", "chapterInput_" + timestamp);

  button.setAttribute("type", "button");
  button.setAttribute("onClick", "redirect()");
  button.setAttribute("id", "editBtn_" + timestamp);
  button.innerHTML = "Edit";

  div.setAttribute("id", "chapterItem_" + timestamp);

  del_button.setAttribute("id", "delBtn_" + timestamp);
  del_button.innerHTML = "Delete Chapter";
  del_button.setAttribute("onClick", "removeElement(this.id)")

  // 组装元素并追加到列表末尾
  div.appendChild(input)
  div.appendChild(button)
  div.appendChild(del_button);
  var list = document.getElementById("spawnList");
  list.appendChild(div);

  // 设置章节相关属性
  input.setAttribute("class", newChapterNumber);
  button.setAttribute("class", newChapterNumber);
  div.setAttribute("class", newChapterNumber);
  del_button.setAttribute("class", newChapterNumber);
  input.setAttribute("index", newChapterNumber);
  button.setAttribute("index", newChapterNumber);
  div.setAttribute("index", newChapterNumber);
  del_button.setAttribute("index", newChapterNumber);
}

总结

核心问题就是按钮类型默认触发了表单提交,加上type="button"就能解决;同时修正ID的设置方式,避免后续出现其他潜在bug。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:06:39