2017-06-04 49 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); 
    });