javascript - 带有 id 参数的多个 div 和 onclick 按钮的问题
问题描述
我正在尝试为学校项目制作通知系统,不允许使用 jQuery!每次有通知时,我都会创建一个带有 onclick 按钮的 div,以确认以 id 作为参数的通知。
然后我的函数 JavaScript 获取 div 并使用 ajax 将通知传递给 SQL 中的 1 状态,最后关闭 div。当我只有一个通知时,它工作得很好,但是当有多个 div 时,我的脚本似乎无法关闭每个通知,我需要刷新我的页面来关闭每个 div。
我的代码:
foreach($notifs as $notif){
$id = $notif["id"]; ?>
<div id="notifAlert">
<p><?= $notif["content"]; ?><br> <button onclick="seenNotif(<?= $id; ?>)">OK</button></p>
</div>
<?php } } ?>
function seenNotif(idNotif){
console.log(idNotif);
const divNotif = document.getElementById("notifAlert");
const footer = document.getElementById("foot");
const req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState === 4){
footer.removeChild(divNotif);
}
};
req.open("GET", "notifStatut.php?idNotif="+idNotif);
req.send();
}
require ("functions.php");
$idNotif = $_GET["idNotif"];
$connection = connectDB();
$query = $connection->prepare("UPDATE notifications SET statut = :statut WHERE id = :idNotif");
$query->execute([
"statut" => 1,
"idNotif" => $idNotif
]);
解决方案
如前所述, id 必须是唯一的。最简单的解决方法是改变
在 PHP 中
<div id="notifAlert">
到
<div id="notifAlert<?= $id ?>">
(添加$id
到 id 以使其唯一)
在javascript中
document.getElementById("notifAlert")
到
document.getElementById("notifAlert"+idNotif)
Th 应该得到你想要的 div。
推荐阅读
- sql - 使用Inner Join的SQL多表查询问题
- ios - Firebase 删除后无法创建文档
- javascript - 反应:过滤状态
- r - 如何创建一个表,其中第一个表中的行也匹配 R 中第二个表的行中的 3 列
- concurrency - Futures 的完成与就绪方法:Rust 与基于运行时的语言
- c++ - 如何在 Cython 中添加链接器标志?
- python - 将两个 DataFrame 的列之间的重叠计算为方形共现矩阵
- macos - zsh 显示当前目录,如果不是 MacOS 上的主目录
- php - 更改为弹性 IP 后,WordPress 站点在 AWS 上关闭
- javascript - Vue Material Kit PRO 选择活动选项卡