网页通讯录项目:表格数据瞬消、JS函数偶发失效问题求助
通讯录项目问题修复方案
问题1:数据添加后立即消失
这是因为你用了type="submit"的按钮,点击后会触发表单的默认提交动作,直接刷新页面,新添加的表格行自然就没了。有两种简单修复方式:
方式一:修改按钮类型
把HTML里的提交按钮从<input>改成<button>,并设置type="button":
<button id="btnSubmit" type="button" onclick="addContact()">添加联系人</button>
方式二:在函数里阻止默认事件
如果不想改按钮类型,就在addContact函数开头添加阻止默认行为的代码:
function addContact(event) { event.preventDefault(); // 阻止表单默认提交 // 原来的代码... }
同时HTML里的按钮要传event参数:
<input id="btnSubmit" type="submit" onclick="addContact(event)">
问题2:函数偶尔失效
原代码里的DOM查询用了getElementsByTagName,这是动态集合,在DOM变化时会自动更新,可能导致循环时出现异常。另外,当表格为空时,搜索函数会因为找不到单元格报错。下面是优化后的代码:
优化后的JavaScript
function addContact(event) { event.preventDefault(); // 阻止表单提交刷新页面 const name = document.getElementById('inpName').value.trim(); const tel = document.getElementById('inpTel').value.trim(); const address = document.getElementById('inpAddress').value.trim(); // 空值判断,避免添加空行 if (!name) return; const tbody = document.querySelector('#tab tbody'); const row = tbody.insertRow(); const nameCell = row.insertCell(0); const telCell = row.insertCell(1); const addressCell = row.insertCell(2); nameCell.textContent = name; telCell.textContent = tel; addressCell.textContent = address; // 清空输入框 document.getElementById('inpName').value = ''; document.getElementById('inpTel').value = ''; document.getElementById('inpAddress').value = ''; } function search() { const searchInput = document.getElementById('searchInput').value.toLowerCase().trim(); const rows = document.querySelectorAll('#tab tbody tr'); rows.forEach(row => { const nameCell = row.querySelector('td:first-child'); if (!nameCell) return; const name = nameCell.textContent.toLowerCase(); row.style.display = name.includes(searchInput) ? '' : 'none'; }); }
优化点说明
- 用
querySelector/querySelectorAll替代动态集合查询,结果更稳定; - 添加空值判断,避免添加空联系人;
- 用
textContent替代innerHTML,更安全(避免XSS风险); - 搜索函数用
forEach遍历,逻辑更清晰,避免动态集合导致的循环异常; - 增加
trim()处理输入内容,避免空格干扰搜索。
完整HTML(仅修改按钮部分)
<h1 id="welcome">Michas Address Book</h1> <div class="inpContainer"> <form name="eingabe"> <input placeholder="输入姓名..." type="text" id="inpName"><br> <input placeholder="输入电话..." type="tel" id="inpTel"><br> <input placeholder="输入地址..." type="text" id="inpAddress"><br> <button id="btnSubmit" type="button" onclick="addContact()">添加联系人</button> </form> </div> <div class="conSearch"> <input type="text" id="searchInput" placeholder="搜索..."> <button onclick="search()">搜索</button> </div> <table id="tab"> <thead> <tr> <th>姓名</th> <th>电话</th> <th>地址</th> </tr> </thead> <tbody> </tbody> </table>
CSS部分无需修改,保持原样即可。
内容的提问来源于stack exchange,提问作者Synav
相关产品推荐
相关产品推荐

