[英]I can't take the value attribute on button | jQuery AJAX
我為刪除按鈕制作了ajax腳本,並在數據庫表中具有基於id的數據屬性。 這是HTML:
<textarea name="komentar" id="komentar" cols="30" rows="10"></textarea><br>
<input type="submit" name="submit" id="submit" value="Submit"><br>
<br><br><hr><br>
<!-- Komentar akan ada di dalam sini -->
<div id="komentar_wrapper">
<?php
include_once 'db.php';
$query = "SELECT * FROM komentar ORDER BY id DESC";
$show_comments = mysqli_query($db, $query);
foreach ($show_comments as $comment) { ?>
<p id="komentar_<?php echo $comment['id']; ?>"><?php echo $comment['komentar']; ?>
<!-- data-id-> data attribute, buat spesifik id mana yang mau di hapus -->
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment['id']; ?>">Delete</button>
</p>
<?php } ?>
</div>
當我嘗試控制台數據ID時,它不會在控制台上顯示該值。 這是腳本:
$(".hapus_komentar").on("click", function() {
console.log($(this).attr("data-id"));
});
當我單擊按鈕時,它說未定義,我認為它應該基於按鈕的data-id打印id
試試這個,我為您准備了一個演示代碼,運行正常
<?php
$as = array(1,2,3,4,5,6,7);
foreach ($as as $comment) { ?>
<p id="komentar_<?php echo $comment ?>"><?php echo $comment; ?>
<button id="button_hapus" class="hapus_komentar" data-id="<?php echo $comment; ?>">Delete</button>
</p>
<?php
}
?>
<script type="text/javascript">
$(".hapus_komentar").on("click", function() {
alert($(this).attr("data-id"));
//console.log($(this).attr("data-id"));
});
</script>
使用Jquery.data() 。 並使用事件委托,因為您的按鈕是動態生成的。
$(document).on("click",".hapus_komentar",function() {
console.log($(this).data("id"));
});
您可以使用$(this).data("id")
來獲取ID。
您的代碼是正確的。 只需簽入HTML weather data-id就會有價值。 也許這就是您沒有獲得適當價值的原因。 同樣,您已經在循環中使用了該按鈕,因此請確保在單擊單個按鈕時將獲得所有按鈕的數據ID。
$(".hapus_komentar").on("click", function() {
console.log($(this).data("id"));
});
現在使用這個。
$(document).on("click",".hapus_komentar",function() {
console.log($(this).attr("data-id"));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.