问题描述
我有一些 html,我将其转换为模板字符串并在选中复选框时收到上述错误,我知道它与 ${currentRow} 有关,只是不知道为什么会这样
function RowChecked(row) {
...
}
const currentRow = ds.find(f => f.ItemID === itemId);
return `<input id='${currentRow.Area}_${currentRow.ItemKey}' type='checkBox' class='checkBox' onChange='RowChecked(${currentRow})' />`;
解决方法
我不会这样做,但你需要使用 JSON.stringify
return `<input id='${currentRow.Area}_${currentRow.ItemKey}' type='checkbox' class='checkbox' onChange='RowChecked(${JSON.stringify(currentRow)})' />`;
但如果其中一个值包含 '
,这将失败。
更好的解决方案是生成 DOM 元素并将它们添加到 DOM。您可以添加引用该对象的事件处理程序。
接下来最好的事情是建立一个 id 的映射/对象并通过 id 引用记录。
查看您的代码,您正在执行大量循环以查找记录。
ds.find(f => f.ItemID)
所以如果你只是把它变成一个对象,它就会变成一个简单的查找
const lookup = ds.reduce((acc,f) => { acc[f.ItemID] = f; return acc; },{});
现在在您的代码中,您可以传递 id 并获取它。查找代码消失了,您只需通过 id 引用对象即可。