使用JQuery从动态按钮获取ID

时间:2019-03-04 02:57:29

标签: 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中获得警报。 请给我建议。

1 个答案:

答案 0 :(得分:2)

不要使用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的“”,有些编辑器会在您键入时添加它们,以使您保持警惕。
相关问题