如何在 Golang 中遍历数据并在 Javascript 中使用时创建唯一 ID

How to create unique IDs when ranging over data in Golang and use in Javascript

我正在从服务器获取数据并迭代它以创建一个 table,然后我使用一个表单使用 javascript 将 id 存储到本地存储。这是代码片段

<table>
    <tr><th>Product ID</th></tr>
    {{range .}}
    <td ><form onsubmit="save_data()" action="/" method="get"><button class="btn btn-info pid" id="pid" name="{{.puid}}" value="{{.puid}}">Update</button></form></td>
    {{end}}
<table>

<script>

function save_data() {
  var input = document.getElementByID("pid");
  localStorage.setItem("id", input.value); 

}   

</script>

但是每次,无论我点击哪个 table 行的 "update" 按钮,每次都只会存储第一个 table 行元素的 ID。 有没有一种方法可以生成唯一 ID 并在遍历数据时在 Javascript 中引用它。 谢谢

在循环中你有

<button class="..." id="pid" name="{{.puid}}" value="{{.puid}}">Update</button>

这意味着所有按钮都具有 id 具有相同值 pid 的属性。这是一个错误,因为 id-s 在文档中必须是唯一的。当你打电话给

document.getElementById("pid");

返回与 id="pid" 匹配的第一个元素。这就解释了为什么 "only the ID of the first table row element is getting stored".

要为每一行创建唯一的 ID,您可以使用

{{range $index, $value := .}}
...<button class="..." id="pid{{$index}}" name="{{$value.puid}}" value="{{$value.puid}}">Update</button>...
{{end}}

但是当您的 save_data() 事件触发时,您会遇到如何知道提交了哪个表单的问题。要解决这个问题,您可以将当前表单或行 ID 作为参数发送,例如

{{range $index, $value := .}}
<td><form onsubmit="save_data(this, {{$index}})" action="/" method="get">...</form></td>
{{end}}

function save_data(form, rowno) {
  var input = document.getElementById("pid"+rowno);
  localStorage.setItem("id", input.value); 
}