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

前端开发:提交form表单时如何阻止页面自动刷新

表单提交触发页面刷新是浏览器的默认行为,你可以通过阻止事件的默认动作解决该问题,同时你提供的代码存在两处命名笔误也需要修正,否则会抛出变量未定义的报错。

修复方案

  • 给事件回调函数传入事件对象参数,调用preventDefault()方法阻止表单默认提交刷新行为
  • 修正函数名、变量名的拼写错误

修复后的完整代码如下:

const changeColour = (e) => {
  // 阻止表单默认提交行为
  e.preventDefault();
  console.log("Submitted");
  const colourForm = document.getElementById("testForm");
  const newColour = colourForm.querySelector("input").value;
  // 修正变量名拼写错误
  console.log(newColour);
};

const newForm = vehicle.querySelector(".vehicle-colour");
// 修正回调函数名拼写错误
newForm.addEventListener("submit", changeColour);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:24:06