JavaScript调用add_row未定义报错 表格无法添加行如何解决
问题根因
报错Uncaught (in promise) ReferenceError: add_row is not defined的直接原因是:你在事件回调中调用了add_row自定义方法,但代码中没有提前实现这个方法,导致调用失败,数据无法插入表格。
修复方案
方案1:实现add_row自定义函数
在你的现有代码开头位置新增如下函数定义,原有调用逻辑不需要修改即可正常运行:
function add_row(tableId, cellValues) { // 获取目标表格元素 const table = document.getElementById(tableId); // 校验并生成tbody容器,避免表头和数据混乱 let tbody = table.querySelector('tbody'); if (!tbody) { tbody = document.createElement('tbody'); table.appendChild(tbody); } // 插入新行 const newRow = tbody.insertRow(); // 依次插入单元格内容 cellValues.forEach(value => { const cell = newRow.insertCell(); cell.textContent = value; }); }
方案2:直接在回调中写插入逻辑,无需单独定义函数
你也可以删掉原有add_row调用,把插入逻辑直接写到事件回调中,完整修改后的代码如下:
document.getElementById("latestPairs").innerHTML = `<table class="table table-dark table-striped table-hover" id="latest"></table>`; const table = document.getElementById("latest"); const rowHeader = `<thead> <tr> <th>Token0</th> <th>Token1</th> <th>Pair</th> </tr> </thead>` table.innerHTML += rowHeader; // 提前创建tbody容器,统一存放数据行 const tbody = document.createElement('tbody'); table.appendChild(tbody); pcsfactoryC.events.PairCreated({fromBlock:'latest'}) .on('data', async function(event){ let token0 = event.returnValues['token0']; let token1 = event.returnValues['token1']; let getPair = event.returnValues['pair']; console.log(token0 + " " + token1); // 直接插入新行和对应内容 const newRow = tbody.insertRow(); newRow.insertCell().textContent = token0; newRow.insertCell().textContent = token1; newRow.insertCell().textContent = getPair; }) .on('error', console.error);
内容的提问来源于stack exchange,提问作者everything is wrong
相关产品推荐
相关产品推荐

