php - 使用 JQuery 从动态按钮获取 ID

标签 php jquery html

我有用于从数据库中获取值的 php 文件。 我无法从结果中获得一个动态的 id 按钮。 我做错了吗?

这是我的代码

<!DOCTYPE HTML>
<html>
<head>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script>src="jquery-3.3.1.js"</script>
</head>
<body>
    <div class="container">
        <?php
        include("koneksi.php");
        $sql = "SELECT * FROM data_cv";
        $result = $conn->query($sql);
        ?>
        <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Nama</th>
                    <th>Nomor Identitas</th>
                    <th>Tempat Lahir</th>
                    <th>Tanggal Lahir</th>
                    <th>Jenis SIM</th>
                    <th>Masa SIM</th>
                    <th>Nomor SKCK</th>
                    <th>Pendidikan</th>
                    <th>Nomor Telepon (Handphone)</th>
                    <th>Keterangan</th>
                    <th>Terima Berkas</th>
                    <th>Tindakan</th>
                </tr>
            </thead>
            <?php
            while ($row = mysqli_fetch_array($result)) {
                echo '
                <tr>
                <td>'.$row["nama"].'</td>
                <td>'.$row["id_ktp"].'</td>
                <td>'.$row["tempat_lahir"].'</td>
                <td>'.$row["tanggal_lahir"].'</td>
                <td>'.$row["jenis_sim"].'</td>
                <td>'.$row["masa_sim"].'</td>
                <td>'.$row["no_skck"].'</td>
                <td>'.$row["pendidikan"].'</td>
                <td>'.$row["no_telp"].'</td>
                <td>'.$row["keterangan"].'</td>
                <td>'.$row["terima_berkas"].'</td>
                <td><button id= "'.$row['id_ktp'].'" value="Accept"">Panggil</button></td>
                </tr>
                ';
            }
            $conn->close();
            ?>
            <script>
            $("button").click(function() {
            alert(this.id);
            });
        </table>
        </div>
    </div>
</body>
</html>

我的 php 文件结果是这样的

php file result

我希望当我点击按钮时,我会根据 php 值从他们的 id 中得到警报。 请给我建议。

最佳答案

不要使用 id而是使用 data- 属性,然后使用一个类来定位按钮,例如:

<button data-id="'.$row['id_ktp'].'" class="valueButton"></button>

然后在您的 jQuery 中,您可以使用数据 api 获取值。

<script>
$(".valueButton").click(function() {
  alert($(this).data('id'));
});
</script>

我忽略了以下内容:

  • 脚本标签错误<script>src="jquery-3.3.1.js"</script>
  • 缺少 <tbody>
  • 并小心使用 auto 的“””,一些编辑器会在您键入时添加,以保持您的警觉。

关于php - 使用 JQuery 从动态按钮获取 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976041/

相关文章:

php - 在两台不同的服务器上使用具有相同 redis 版本的 Laravel redis,其中一台内存使用量更大

php - 将 URL ID 更改为简单文本

php - 如何在回调函数中注释 $this

在 Rails 应用程序中多次触发 Javascript 事件?

HTML 输入 - 已填入文本

php - 在 Linux 中配置虚拟主机和本地主机重定向到 xampp 文件夹

javascript - 多色线

javascript - 转换 JSON 数据并在复选框、文本、下拉或单选输入类型中实现值的最佳方法?

javascript - 如何禁用和重新启用隐藏/可见元素的 tabindex?

javascript - 将列表嵌入为字符串 javascript 的一部分