首页 > 解决方案 > PHP Js 只能使用表格的第一行(按钮)

问题描述

我是新手,仍然对我的问题感到困惑,所以这是我的 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>

据说当点击每一行旁边的按钮时,会出现一个弹出窗口,但只有第一行有效,其他按钮什么也不做。我确实已经搜索了 2 个小时左右的这个问题,他们中的大多数都在谈论唯一 id,但是我该如何实现或解决这个问题。

这是一个脚本

        document.getElementById('myId').addEventListener("click", function () {
            document.querySelector('.bg-modal').style.display = "flex";
        });

非常感谢您的帮助,非常感谢。

标签: javascriptphphtml

解决方案


首先,您应该为每个 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>


推荐阅读