当点击按钮触发 JavaScript 更新 DOM 时,若按钮位于 <form> 内且未阻止默认提交行为,浏览器会自动提交表单并刷新页面,导致刚写入的 innerHTML 瞬间丢失——这是前端开发中常见却易被忽视的“假性失效”。
当点击按钮触发 javascript 更新 dom 时,若按钮位于 `
在构建基于表单的交互式评分工具(如澳大利亚慈善组织评估系统)时,开发者常遇到这样一种“诡异现象”:console.log() 能正确输出元素值,但 document.getElementById().innerHTML = … 却看似“不生效”。问题根源并非 DOM 未加载、选择器错误或脚本执行顺序不当,而是 表单的默认提交行为触发了整页刷新,覆盖了刚刚写入的动态内容。
HTML 中 <form> 元素内的 <button>(无 type 属性时默认为 type=”submit”)点击后会触发表单提交。即使 <form action=””> 为空,浏览器仍会执行一次 GET 请求(重载当前页),导致所有 JavaScript 动态修改的 DOM 状态瞬间清空。
只需两步即可彻底解决:
以下是修复后的完整代码示例:
立即学习 “ 前端免费学习笔记(深入)”;
<h1>Organisation Score Calculator</h1> <form action=""> <h4>Input the name of the charity.</h4> <input type="text" id="nameOfOrganisation"> <h4>Which state/territory does this organisation service?</h4> <select name="state" id="state"> <option value="VIC">VIC</option> <option value="NSW">NSW</option> <option value="ACT">ACT</option> <option value="QLD">QLD</option> <option value="NT">NT</option> <option value="TAS">TAS</option> <option value="WA">WA</option> </select> <br><br> <button onclick="main(event)">Get score!</button> <p id="namePlaceholder"></p> <p id="statePlaceholder"></p> </form> <script> function getNameOfOrganisation() { return document.getElementById("nameOfOrganisation").value || "(not provided)"; } function getStateOfOrganisation() { const state = document.getElementById("state").value; switch (state) {case "VIC": return 1; case "NSW": return 0.5; default: return 0;} } function main(e) {e.preventDefault(); // ✅ 关键:阻止表单默认提交 const name = getNameOfOrganisation(); document.getElementById("namePlaceholder").innerHTML = `Name of organisation: ${name}`; const statePoints = getStateOfOrganisation(); document.getElementById("statePlaceholder").innerHTML = `Points scored for state/territory: ${statePoints}`; } </script>
document.querySelector('button').addEventListener('click', main);
掌握 preventDefault() 不仅能解决当前问题,更是理解 Web 表单交互机制的关键一环——它让开发者真正掌控用户行为,而非被动响应浏览器默认逻辑。
宝塔面板如何限制面板访问IP?防止未授权设备登录你的宝塔面板后台
SQL如何在触发器中调用外部接口_UDF用户自定义函数扩展实现