【问题标题】:I am trying to add a for loop inside html, ? but the for loop shows error我正在尝试在 html 中添加一个 for 循环,?但 for 循环显示错误
【发布时间】:2021-04-16 11:07:30
【问题描述】:

我在 {while add this for loop in my table 下看到一条红色波浪线,我在这里缺少什么。

var cartHtml = `<table>
                  <tr>
                     <th> Item</th>
                     <th> Description</th>
                     <th> Price</th>
                     <th> Qty</th>
                     <th> Totall</th>
                  </tr>
                  <tr>`
                     ${for (var i=0; i<5; i++){
                       `<td>data</td>`
                     }}
                 `</tr>
                 </table>`

【问题讨论】:

  • 那(红色波浪线)是一个语法错误;你需要连接你正在构建的 html 字符串
  • 我正在尝试用反引号来做到这一点,你能告诉我如何准确连接吗?
  • 使用“+”连接
  • 好吧也试试!!
  • @Wimanicesir 字符串插值不需要连接,您不能连接 ${}

标签: javascript html for-loop frontend


【解决方案1】:

您可以创建一个循环函数并将所需的返回数据保存在另一个变量中,而不是尝试直接在 innerHTML 中执行 for 循环:

let loopdata;

const loop = () => {
    for (let i = 0; i < 5; i++) {
     loopdata+=`<td>data</td>`;
    }
    return loopdata;
  };
  
  var cartHtml = `
   <table>
  <tr>
     <th> Item</th>
     <th> Description</th>
     <th> Price</th>
     <th> Qty</th>
     <th> Totall</th>
  </tr>
  <tr>
  ${loop()}
  </tr>
  </table>`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多