【问题标题】:unexpected token error when using onclick使用 onclick 时出现意外的令牌错误
【发布时间】:2017-06-04 21:53:19
【问题描述】:

这是我的代码

  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 的意外令牌错误。我很确定这是一个非常愚蠢的问题,但我就是不知道它在哪里。

【问题讨论】:

    标签: javascript arrays string ecmascript-6


    【解决方案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('');
    

    【讨论】:

    • 好的,所以我无法添加此功能,例如:function clickHere() {console.log('hi')}
    • 您可以在&lt;script&gt; 块中定义函数,然后使用onclick="clickHere()"。这是使用 Javascript 函数的正常方式。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      最后我用了这个解决方案,很可惜,因为另一个更短:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-23
        相关资源
        最近更新 更多