JavaScript点击按钮显示表格失效、表格提前渲染问题求助
问题修复方案
问题根因
- 按钮点击事件绑定错误:
addEventListener的第二个参数需要传入函数引用,你写的tablechange(3)会在代码执行到这一行时直接调用函数,所以请求加载完成后表格就提前渲染了,同时没有给按钮绑定实际的点击回调,导致点击按钮无响应 - 表格渲染逻辑冗余:
document.body.append(table)写在了循环内部,每次遍历数据都会重复插入表格到页面 - 没有做旧数据清空:重复点击按钮会导致表格数据不断叠加
修复后完整代码
var request = new XMLHttpRequest(); request.open('GET', 'https://raw.githubusercontent.com/Rajavasanthan/jsondata/master/pagenation.json', true); request.send(); request.onload = function () { var data = JSON.parse(request.response); console.log(data); // 初始化表格结构 var table = document.createElement('table'); table.setAttribute('class', 'table'); var thead = document.createElement('thead'); thead.setAttribute('class', 'thead-dark') var tr = document.createElement('tr'); var tbody = document.createElement('tbody'); var th1 = document.createElement('th') th1.innerHTML = 'id' var th2 = document.createElement('th'); th2.innerHTML = 'Name' var th3 = document.createElement('th'); th3.innerHTML = 'Email'; tr.append(th1, th2, th3); thead.append(tr); table.append(thead); table.append(tbody); // 创建按钮 var divis = document.createElement('div'); divis.setAttribute('style', 'padding:20px'); var button = document.createElement('button'); button.innerHTML = "click me"; // 绑定事件改为传入函数引用,需要传参的话包裹在匿名函数内 button.addEventListener('click', function() { tablechange(3); }); divis.append(button); document.body.append(divis); function tablechange(i = 1) { // 清空之前的表格内容,避免重复叠加 tbody.innerHTML = ''; for (let x = i * 5; x < ((i + 1) * 5); x++) { let k = data[x]; var td1 = document.createElement('td'); var td2 = document.createElement('td'); var td3 = document.createElement('td'); td1.innerHTML = k.id td2.innerHTML = k.name; td3.innerHTML = k.email; var tr = document.createElement('tr'); if (x % 2 === 0) tr.setAttribute('style', 'background-color:#d3d3d3'); tr.append(td1, td2, td3); tbody.append(tr); } // 表格只需要插入一次到页面 if (!document.body.contains(table)) { document.body.append(table); } } }
改动说明
- 修正了事件绑定逻辑:将
tablechange(3)包裹在匿名函数中传入addEventListener,仅在点击按钮时才触发执行 - 调整了表格插入逻辑:将
document.body.append(table)移出循环,且判断表格未插入页面时才执行插入,避免重复操作 - 新增tbody清空逻辑:每次调用
tablechange前先清空已有内容,避免重复点击时数据叠加 - 调整了表格结构挂载逻辑:tbody提前挂载到table上,不用每次循环重复挂载
内容的提问来源于stack exchange,提问作者Sathwic
相关产品推荐
相关产品推荐

