这是我的代码
const products = productArray.map(product =>
`
<tr>
<td>${product.id}</td>
<td>${product.type}</td>
<td>${product.price}</td>
<td><button onclick="${() => console.log('hello world')}">Examine</button></td>
</tr>
`
);
return tableBody.innerHTML = products.join('');
答案 0 :(得分:1)
您无法替换模板文字中的函数。它只是插入函数的源代码。
在这种情况下,它也没有什么意义。您可以简单地将函数体放在onclick
属性中。
const products = productArray.map(product =>
`
<tr>
<td>${product.id}</td>
<td>${product.type}</td>
<td>${product.price}</td>
<td><button onclick="console.log('hello world')">Examine</button></td>
</tr>
`
);
return tableBody.innerHTML = products.join('');
答案 1 :(得分:0)
我建议您使用clientide模板引擎来避免此类问题。例如mustachejs。
但关于修复(试试这个):
NumPad
&#13;
const tableBody = document.getElementById('productsTable');
const productArray = [
{id: 1, type: 'something', price: 100},
{id: 2, type: 'samething', price: 120}
];
const products = productArray.map(product =>
`
<tr>
<td>${product.id}</td>
<td>${product.type}</td>
<td>${product.price}</td>
<td><button onclick="(() => {alert('${product.id} ${product.type}');})()">Examine</button></td>
</tr>
`
);
tableBody.innerHTML = products.join('');
&#13;
答案 2 :(得分:0)
At the end I used this solution, it's a pitty because the other was shorter:
const products = productArray.map(product => {
const tr = document.createElement('tr');
const td1 = document.createElement('td');
const td2 = document.createElement('td');
const td3 = document.createElement('td');
const td4 = document.createElement('button');
td4.addEventListener('click', () =>
processSearch(product.id)
);
td1.appendChild(document.createTextNode(product.id));
td2.appendChild(document.createTextNode(product.type));
td3.appendChild(document.createTextNode(product.price));
td4.appendChild(document.createTextNode('Examine'));
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
return tableBody.appendChild(tr);
});