我有用于从数据库中获取值的 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 值从他们的 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/