【问题标题】:How can i change values dynamically in for loop which is in ejs file如何在 ejs 文件中的 for 循环中动态更改值
【发布时间】:2021-07-05 03:17:13
【问题描述】:

我已将节点 js 文件中的数据提取到我的 ejs 文件中。像这样:

  <% for(var i=0; i < data.length; i++) { %>
                <tr>
                  <td id="value"><%= i+1 %></td>
                  <td ><%= data[i] %></td>
                  <td><button onclick="myFunction()" id="btn-download" class="btn btn-light"><i class="fas fa-file-download"></i>indir</button></td>
                </tr>
             <% } %>

它正确地呈现数据。但是当我想在 myFunction() 中使用数据索引时,它会显示第一个索引。这是 myFunction():

<script>
  function myFunction() {
       var text=document.getElementById("value").innerHTML;
        /*var filename="data.txt";
        download(filename,text);*/
        console.log(text)
}
</script>

我想拥有

1
2
3

但我只有

1
1
1

怎样才能得到我想要的输出?

【问题讨论】:

  • 你好,其中一种方法是在函数中直接传递i+1onclick="myFunction(i+1)",然后在函数中直接访问。
  • 你正在使用id 选择器,这就是为什么它只会显示1
  • 您生成的 HTML 无效。不允许有多个具有相同 ID 的元素。 ID 必须是唯一的。

标签: javascript html ejs


【解决方案1】:

问题是您使用了多个具有相同 id 的元素:

//Step 1. Give unique ids
<td id="value<%= i+1 %>"><%= i+1 %></td>

//Step 2. Pass param to function and use data-id to pass 'ID' of <td>
<td><button onclick="myFunction()" id="btn-download" class="btn btn-light" data-id="value<%= i+1 %>"><i class="fas fa-file-download"></i>indir</button></td>

//Step 3. Use data-id in the javascript function to refer to the <td>
function myFunction() {
      var buttonId=event.target.getAttribute("data-id");;
        var text= document.getElementByID(buttonId).innerHTML;
/*var filename="data.txt";
        download(filename,text);*/
        console.log(text)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-13
    • 2020-10-13
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多