首页 > 解决方案 > 带有 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
    ]);

标签: javascriptphpajax

解决方案


如前所述, id 必须是唯一的。最简单的解决方法是改变

在 PHP 中

<div id="notifAlert">

<div id="notifAlert<?= $id ?>">

(添加$id到 id 以使其唯一)

在javascript中

document.getElementById("notifAlert")

document.getElementById("notifAlert"+idNotif)

Th 应该得到你想要的 div。


推荐阅读