我正在浏览一个简单的foreach循环以获取“博客文章”。它显示基本的博客信息,回复和删除按钮。当我选择“回复”按钮时,出现在回复按钮下方的一个小表格需要填写。问题是,我将变量传递给的函数仅获取表单的最后一个ID。如何将我的function或div元素更改为每个实例唯一?
我尝试在“ id”和函数上设置PHP @echo变量,我已经检查了所有的10个折叠括号。我尝试使用其他GetElementBy ...方法。我开始研究Jquery,但我只想用PHP / Javascript完成此工作。
<?php foreach ($mainentries as $entry) :
$subentryID = $entry['SubEntryID'];
if ($subentryID == "0")
{ ?>
<div><tr><td><?php echo ('#'.$entry['EntryID'].' - ')?></td>
<td><?php echo $entry['Body']; ?></td>
<br />
<?php foreach($subentries as $subentry) : ?>
<?php if ($subentry['SubEntryID'] == $entry['EntryID'])
{ ?>
<div id="subposts">
<td><td><td>#<?php echo $subentry['EntryID'];?></td><br>
<td>
<?php echo $subentry['Body']; ?>
</td></td></td>
</div>
<?php } endforeach; ?>
<br />
<td>
<button onclick="cookiechecksub()">Reply</button>
<?php echo $entry['EntryID'];
$subform = $entry['EntryID']; ?>
<div id="<?php echo $subform?>" style="display:none">
<form action="Add_subentry.php" method="post" id="Add_subentry">
<label>Title:</label><br />
<input type = "text" name="Title" class="Title"/> <br />
<label>Body</label><br />
<div class="area">
<input type = "textarea" name="Body" class="Body"/><br />
</div>
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<input type=submit id="btnReply" value="Submit Reply"/>
</form>
</div></td>
<td>
<form action="Delete_entry.php" method="post" id="Delete_entry">
<input type="hidden" readonly="true" name="EntryID" value="<?php echo $entry['EntryID']; ?>" />
<?php if ($userid == 1)
{ ?>
<input type="submit" id="btnDelete" value="Delete Post"/>
<?php } ?>
<br /><br />
</form>
</td>
</tr>
</div>
<?php
} endforeach; ?>
<Script>
function cookiechecksub() {
if (!userid) {
if (confirm("Please log in first")) {
window.location.replace("http://localhost/alexdes/login-logout.php");
}
}
else {
TryAddSubPost();
}
}
function TryAddSubPost()
{
var x = document.getElementById("<?php echo $subform?>");
if (x.style.display === "none")
{
x.style.display="block";
}
else
{
x.style.display="none";
}
}
</Script>
答案 0 :(得分:1)
这是因为您在js函数中尤其是在TryAddSubPost
中使用了php echo
将其更改为这样:
<script>
function cookiechecksub(id) {
if (!userid) {
if (confirm("Please log in first")) {
window.location.replace("http://localhost/alexdes/login-logout.php");
}
}
else {
TryAddSubPost(id);
}
}
function TryAddSubPost(id)
{
var x = document.getElementById(id);
if (x.style.display === "none")
{
x.style.display="block";
}
else
{
x.style.display="none";
}
}
</script>
并仅在调用函数时使用php中的id,例如:
<button onclick="cookiechecksub('<?php echo $entry['EntryID']?>')">Reply</button>
答案 1 :(得分:0)
给cookiechecksub
一个参数,并将其传递给TryAddSubPost
<button onclick="cookiechecksub('<?=$entry['EntryID']?>')">