1 回答

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
html 文檔中元素的id屬性應(yīng)該是唯一的,并且您可以使用$("#exec")僅選擇具有該 id 的第一個(gè)元素來(lái)選擇元素。
您可以移動(dòng)到類選擇器,或使用多個(gè) id 并通過(guò)其他選擇器進(jìn)行選擇:
<body >
<div style="width: 100%;">
<div style="height:700px;overflow:auto;float:left;width: 50%">
<table>
<tr>
<th>Country Name</th>
<th>View</th>
</tr>
{{ range .CountryData }}
<tr>
<td>{{ .Name }}</td>
<td><button class="exec" cid="{{.Id}}">Show</button></td>
</tr>
{{ end }}
</table>
</div>
<div id="response" style="height:700px;overflow:auto;float:left;width: 50%"></div>
</div>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button.exec").on("click", function() {
var urlData = "/country?cid=" + $(this).attr("cid");
$.ajax({
url: urlData,
method: "GET",
success: function(data) {
$("#response").html(data);
},
});
});
});
</script>
如果無(wú)法更改id道具,您可以添加一些其他類并使用其他選擇器。例如 - 您可以將 id 添加到表中,然后選擇該特定表中的所有按鈕:
<table id="table-with-buttons">
...
{{ range .CountryData }}
<tr>
<td>{{ .Name }}</td>
<td><button id="exec" cid="{{.Id}}">Show</button></td>
</tr>
{{ end }}
</table>
在您的代碼中,您可以使用以下方法選擇所有按鈕:
$("#table-with-buttons button").on("click", function() {
....
});
- 1 回答
- 0 關(guān)注
- 87 瀏覽
添加回答
舉報(bào)