意外的标记错误的onclick
问题描述:
这是我的代码意外的标记错误的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('');
答
您不能在模板文字中替换函数。它只是插入函数的源代码。
在这种情况下也没什么意义。您可以简单地将函数体置于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('');
答
我建议您使用客户端模板引擎来避免此类问题。例如mustachejs。
但是关于修复(试试这个):
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('');
<table id="productsTable">
</table>
答
在我用这个解决方案的目的,这是一个贝蒂因为其他更短:
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);
});
OK所以没有办法,我可以添加此功能,例如: function clickHere(){console.log('hi')} –
您可以定义func '