我正在做一个网络应用,让人们安排课程和时间段,我试图让人们可以点击时间段来接受它。目前,该表是从数据库中获取的,并通过以下代码生成。
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>
标签,并与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。