[英]How can i change values dynamically in for loop which is in ejs file
I have fetched data from my node js file into my ejs file.我已将节点 js 文件中的数据提取到我的 ejs 文件中。 Like this:
像这样:
<% 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>
<% } %>
It renders data properly.它正确地呈现数据。 But when i wanted to use data's indexes in myFunction(),it shows me the first index.
但是当我想在 myFunction() 中使用数据索引时,它会显示第一个索引。 This is myFunction():
这是 myFunction():
<script>
function myFunction() {
var text=document.getElementById("value").innerHTML;
/*var filename="data.txt";
download(filename,text);*/
console.log(text)
}
</script>
I want to have我希望有
1
2
3
But i have only但我只有
1
1
1
How can take the output that i want?怎样才能拿走我想要的output?
The problem is that you are using multiple elements with same id:问题是您正在使用具有相同 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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.