2017-06-04 86 views
0

这是我的代码意外的标记错误的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(''); 

我只是不明白为什么我得到这个意外的标记错误,它指向的HTML。我很确定这是一个非常愚蠢的,但我不能得到它在哪里。 enter image description here enter image description here

回答

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(''); 
+0

OK所以没有办法,我可以添加此功能,例如: function clickHere(){console.log('hi')} –

+0

您可以定义func '

0

我建议您使用客户端模板引擎来避免此类问题。例如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>

0

在我用这个解决方案的目的,这是一个贝蒂因为其他更短:

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); 
    });