我正在开发一个Web应用程序,该程序可以使人们安排课程和时间安排,并且正在尝试使人们可以单击时间来接受它。当前,该表是从数据库中检索的,并使用以下代码生成:
function updateSchedules(name = "missing", grade = "missing", date = "missing", time = "missing", status = "missing", id) {
let table = document.getElementById('schedules');
let color;
console.log("Output schedule for " + name);
if (status.toLowerCase() === 'pending') {
color = "background-color:rgb(252, 38, 0)";
} else if (status.toLowerCase() === 'confirmed') {
color = 'background-color:rgb(0, 255, 13)';
} else {
color = 'background-color:rgb(35, 64, 153)';
}
table.innerHTML += `
<tr>
<td>${name}</td>
<td>${grade}</td>
<td id=testday2>${date}</td>
<td id=testtime2>${time}</td>
<td style="${color}">${status}</td>
</tr>`;
}
有没有一种方法可以在表的每一行上添加引用每行唯一ID的按钮,而不仅仅是为每行手动创建按钮和添加事件侦听器?
您必须再添加一个<td>
带有<button>
tag的tag并与onlick事件绑定,并在函数参数中传递unique_id,如下所示:
<td><button type="button" onclick="myfunc(${id})"></button></td>
$ {id}可以是字符串或数字,取决于要求
Note-:
然后编写脚本来处理按钮,例如:
<script>
function myfunc(unique_id){
console.log(unique_id);
// do something
}
<script>
如果将锚标签与按钮(例如)一起使用,则更合适:
<td><a onclick="myfunc(${id}")><button type="button"></button></a></td>
有多种方法可以执行此操作。如果将
this
关键字与jquery结合使用而不是编写纯JavaScript,则更合适。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句