[英]How to get the value of while loop(PHP) using JavaScript?
我在 PHP 中有这个 while 循环
<?php
while ($row = mysqli_fetch_assoc($getPosts)) {
$post_id = $row['post_id'];
echo "<td><a rel='$post_id' id='get_post_id'
onclick='active_del_modal()'>Delete</a></td>";
}
?>
在这个循环中,当我们点击“删除”链接时,变量“$post_id”的值会发生变化。 我想在它发生变化时获取“$post_id”的值。 我试过这个JS代码
function active_del_modal() {
var x = document.getElementById("get_post_id").getAttribute("rel");
alert(x);
}
但它只给了我“$post_id”的最后一个值。 我想在“$post_id”更改时获取每个值,并且该值应该是单独的,而不是像这样的 23 46 545 545 等。我不想使用像 jQuery 这样的任何框架。
方法 1 - 最小变化
onclick='active_del_modal(this)'
你可以使用
function active_del_modal(link) {
var x = link.getAttribute("rel");
alert(x);
}
方法2 - 更好:
window.addEventListener("load",function() {
document.querySeletor("table").addEventListener("click",function(e) {
const tgt = e.target, rel = tgt.getAttribute("rel");
if (rel) alert(rel);
})
})
我建议使用数据属性而不是 rel:
如果您将 id 更改为 class,您可以这样做
window.addEventListener("load",function() {
document.querySeletor("table").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("get_post_id")) {
const id = tgt.dataset.id;
console.log(id);
}
})
})
使用
echo "<td><a data-id='$post_id' class='get_post_id'>Delete</a></td>";
最后,如果链接应该删除该行,您可以这样做
window.addEventListener("load",function() {
document.querySeletor("table").addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.classList.contains("delete")) {
tgt.closest("tr").remove();
}
})
})
使用
echo "<td><button type="button" class='delete'>Delete</button></td>";
rel
属性。 (适当的使用类似于<a href="page2.html" rel="next">
)如果您需要将自定义数据与元素相关联,请使用data-*
属性。addEventListener
和朋友。 function active_del_modal(event) { const button = event.target; const id = button.dataset.postId; console.log({ id }); } document.querySelector("#delete-buttons").addEventListener("click", active_del_modal);
button { border: none; background: none; colour: blue; cursor: pointer; } button:hover { text-decoration: underline; }
<ul id="delete-buttons"> <li><button type="button" data-post-id="$post_id">Delete</button></li> <li><button type="button" data-post-id="foo">Delete</button></li> <li><button type="button" data-post-id="bar">Delete</button></li> </ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.