我对此很陌生,但仍然对我的问题感到困惑,下面是我的php的一个表
<table>
<tr>
<th align="center">ID</th>
<th align="center">Project Name</th>
<th align="center">Due Date</th>
<th align="center">Sub Date</th>
<th align="center">Comment</th>
<th align="center">Status</th>
<th align="center">Option</th>
</tr>
<tr>
<?php
while ($res2=mysqli_fetch_assoc($result2)) {
echo "<tr>";
echo "<td>".$res2['project_id']."</td>";
echo "<td>".$res2['project_name']."</td>";
echo "<td>".$res2['duedate']."</td>";
echo "<td>".$res2['subdate']."</td>";
echo "<td>\"".$res2['comment']."\"</td>";
echo "<td>".$res2['status']."</td>";
//as you can see, id = myId
echo "<td><a href=\"#\" id=\"myId\" class=\"button\">View</a>";
}?>
</td>
</tr>
</table>
据推测,当单击每一行旁边的按钮时,会出现一个弹出窗口,但只有第一行才能工作,而其他按钮则什么也不做。我已经搜索了大约两个小时了,他们中的大多数都谈到了唯一的id,但是我如何实现或修复这个问题。
这是一个脚本
document.getElementById('myId').addEventListener("click", function () {
document.querySelector('.bg-modal').style.display = "flex";
});
非常感谢你的帮助,非常感谢。
发布于 2021-10-24 06:41:08
你可以试试:
[].slice.call(document.querySelectorAll('[id^="myId"]'))
.map(el => el.addEventListener("click", function () {
document.querySelector('.bg-modal').style.display = "flex";
}));
你应该改变你的代码:
$i = 0;
while ($res2=mysqli_fetch_assoc($result2)) {
......
//as you can see,
echo "<td><a href=\"#\" class=\"class-{++$i}\" class=\"button\">View</a>";
}
现在,js代码:
[].slice.call(document.querySelectorAll('[class^="class-"]'))
.map(el => el.addEventListener("click", function () {
document.querySelector('.bg-modal').style.display = "flex";
}));
发布于 2021-10-24 06:44:13
首先,您应该只对每个HTML元素使用唯一ID,如果要创建具有相同行为的多个元素,则使用class
。
将其更改为class
之后,可以通过使用querySelectorAll()
分配一次来选择所有的元素。
下面是一个工作示例:
document.querySelectorAll('button.click').forEach(elem =>
{
elem.addEventListener('click', () => {
document.querySelector('div').style.background = elem.innerText;
});
});
div {
width: 200px;
height: 200px;
}
<button id="1" class="click">green</button>
<button id="2" class="click">blue</button>
<div></div>
发布于 2021-10-24 07:15:08
id应该是唯一的。您不应该在一个页面中使用同一id的两倍。类就是为了达到这个目的。
首先,我们应该在每个按钮上添加一个类,告诉我们这个按钮是用来显示模态的。我们还删除了id,因为它不会是唯一的,在这里也是无用的。
echo "<td><a href=\"#\" class=\"modal-button button\">View</a>";
然后,为了添加侦听器,我们希望针对每个具有我们刚刚添加的新的“模式-按钮”的按钮。正确的方法是使用类来锁定元素,迭代它们并添加侦听器。
document.getElementsByClassName(‘modal-button’).forEach(button => {
button.addEventListener("click", function () {
document.querySelector('.bg-modal').style.display = "flex";
});
})
希望这能帮上忙!
https://stackoverflow.com/questions/69697750
复制