在 JSP 頁面添加 <form> 標籤後,原本正常的動態生成文本框按鈕突然失效。根因是 按鈕的 id 與 JavaScript 函數名同名,導致 form 表單元素集合覆蓋了全局函數引用。
<input type="button" onclick="CreateGInput()" value="創建新工序" id="CreateGInput" />
<input type="button" onclick="CreateCInput()" value="添加工序零件" id="CreateCInput" />
<form> 時:CreateGInput 解析為 window.CreateGInput(全局函數),正常調用。<form> 時:表單元素自動成為 form.CreateGInput(DOM 元素),遮蔽了同名全局函數。onclick="CreateGInput()" 在表單作用域內解析為元素對象,調用失敗拋異常。<input type="button" onclick="window.CreateGInput()" id="CreateGInput" />
<input type="button" onclick="window.CreateCInput()" id="CreateCInput" />
initCreateGInput()、handleCreateCInput()。btnCreateGInput、btnCreateCInput。addEventListener 綁定事件,完全分離 HTML 與 JS。const FormManager = {
init() {
document.getElementById('btnCreateGInput').addEventListener('click', this.createGInput);
document.getElementById('btnCreateCInput').addEventListener('click', this.createCInput);
},
createGInput() { /* ... */ },
createCInput() { /* ... */ }
};
FormManager.init();
onclick,便於維護與作用域隔離。這是前端開發中極常見且隱蔽的坑,建立嚴格的命名規範與模塊化習慣可從根源杜絕。