1 回答
![?](http://img1.sycdn.imooc.com/5458655200013d9802200220-100-100.jpg)
TA贡献1856条经验 获得超17个赞
您的代码loadDoc在循环内生成多个函数,因此每个按钮都使用相同的函数(相同的 rowId 静态放置在其中)。
如果您只有一个函数并将 id 作为参数传递,那就更好了,如下所示:
<?
$query = $db->query("SELECT * FROM posts ORDER BY id DESC LIMIT $limit");
if($query->num_rows > 0){ ?>
<div class="posts_list">
<?php
while($row = $query->fetch_assoc()){
$postID = $row['id'];
?>
<div class="list_item">
<h2><?php echo $row["title"] ?></h2>
<!-- Pass Id into the function -->
<button type="button" onclick="loadDoc(<?php echo $row['id'] ?>)" >View</button>
</div>
<div class="item_viewer"><p id="demo"></p></div>
<?php } ?>
</div>
<script type="text/javascript"> // Move JavaScript function out of loop, so that it only exists once in the document
function loadDoc(rowId) { // Pass rowId as argument
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "file/file.php?id=" + rowId, true);
xhttp.send();
}
</script>
<?php echo $pagination->createLinks(); ?>
<?php } ?>
添加回答
举报