jquery - How can I get the buttons being generated in my table to have a dynamic ID?
问题描述
I have a dynamically generated table in which I have buttons for which I need to be able to generate dynamic ids. I will be using the buttons later to (hopefully) grab the info from the table and create alerts based on the data. I can't get the buttons to generate a dynamic id though. I can get them to generate an id, but they have the same ID and aren't dynamic at all.
I've created a function that generates IDs and then appends the button class that I am targeting with the new ID. I have a table that is generated with jQuery using JSON data and all of that works. The code I am providing only generates the button IDs as "button2" which makes sense as that would be the next available index I suppose, but I don't know how to get it to generate the appropriate ID for the row in which in resides.
Simple html table that is populated with JSON data
<table id="schoolTable" class="table">
<thead>
<tr>
<th><h4>School Name</h4></th>
<th><h4>Status</h4></th>
<th><h4>Chat</h4></th>
</tr>
</thead>
<tbody id="schoolTableBody">
</tbody>
</table>
jQuery that creates the table and fills it
populateTable = function() {
$.getJSON("/assets/JSON/schools.JSON", function(result) {
$.each(result, function(i){
var schools = result.schools,
output = "",
schoolTableBody = $("#schoolTableBody");
for (var i = 0; i < schools.length; i++) {
buttonIdAdd = function() {
var button = $(".schoolInfoButton").attr("id", "button" + '-' + i);
$(".schoolInfoButton").append(button);
}
output +=
'<tr>' +
'<td>' +
'<h5>' +
schools[i].name +
'</h5>' +
'</td>' +
'<td class="schoolButtonHolder">' +
'<button class="schoolInfoButton">' +
"Get" +
' ' +
schools[i].topic +
' ' +
"Information" +
'</button>' +
'</td>' +
'<td class="chatButtonHolder">' +
'<button class="schoolChatButton">' +
"Chat With" +
' ' +
schools[i].topic +
'</button>' +
'</td>' +
'</tr>';
}
schoolTableBody.html(output);
buttonIdAdd()
});
});
}
I would like the buttons to have an ID based on the row they are in. I suppose the index? I am not sure how to do that as I thought the code provided could possibly work.
解决方案
推荐阅读
- javascript - 对于每个 div insert.before 图像
- android - 如何在 Ejabberd 服务器上从 android 客户端注册新用户
- loops - 自动热键循环的奇怪行为
- c++ - C++、函数表和模板
- wordpress - 每当有人进入产品页面以及按下按钮时,Facebook Pixel 都会触发 AddToCart
- flutter - 使用相机包授予权限会在异常时暂停调试器
- c# - 在版本化 REST API 中使用模块
- sql - 如何剪一张桌子?
- python - 在python中获取2dnumpy数组的前三个最大值
- mysql - 当值是 XX_YY_ZZ 形式但在没有下划线的情况下工作时,使用 TKinter 中的 Entry 时更新 MySQL 中的表会导致错误