有没有更好的方法为php onclick
中的某些内容提供echo
函数赋值?我在点击div
链接或点击<a>
时尝试打开模式<button>
。
<div id="modalBox" class="w3-modal">
<div class="w3-modal-content">
<div class="w3-container">
<span onclick="document.getElementById('modalBox').style.display='none'" class="w3-button w3-display-topright">×</span>
<p>Some text. Some text. Some text.</p>
<p>Some text. Some text. Some text.</p>
</div>
</div>
</div>
<div class="record-container">
<table class="table-record">
<tr>
<th>Title</th>
<th>Date Created</th>
<th>Control</th>
</tr>
<?php
$announcementDaoImpl = new AnnouncementDaoImpl($pdo);
$announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
foreach ($announcementList as $key => $value) {
$announcementTitle = $value->getTitle();
$dateCreated = $value->getDateAdded();
echo "<tr>";
echo "<td>" . $announcementTitle . "</td>";
echo "<td>" . $dateCreated . "</td>";
echo "<td><button onclick='showEditModal()'>" . "Edit" . "</button></td>";
echo "</tr>";
}
?>
</table>
</div>
这一行,
echo "<td><a href='#' onclick='showEditModal()'>" . "Edit" . "</a></td>";
我指定showEditModal()
作为方法,以便在点击编辑按钮后,它将调用此方法以显示模式框。但是,我遇到了双引号和单引号的问题,因为showEditModal()
方法需要参数。
function showEditModal(modalDivId){
var modalBox = document.getElementById(modalDivId);
modalBox.style.display = "block";
}
我甚至试过这个。
echo "<td><button onclick=\"showEditModal('modalBox')\">" . "Edit" . "</button></td>";
没有运气。模态框不会显示。即使是alert()
也不会出现。
如何在echo
上提供参数?
感谢。
答案 0 :(得分:1)
有多种方法可以解决这些问题,其中一个选项是PHPs alternative syntax;
<div class="record-container">
<table class="table-record">
<tr>
<th>Title</th>
<th>Date Created</th>
<th>Control</th>
</tr>
<?php
$announcementDaoImpl = new AnnouncementDaoImpl($pdo);
$announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
foreach($announcementList as $key => $value): ?>
<tr>
<td><?php echo $key->getTitle(); ?></td>
<td><?php echo $value->getDateAdded(); ?></td>
<td>
<a href="#" onclick="showEditModal('modalBox')">Edit</a>
</td>
</tr>
<?php endforeach; ?>
</table>
</div>
答案 1 :(得分:0)
通过正确处理字符串中的引号字符,转义"
,因为字符串分隔符是相同的。
<强>尝试:强>
echo "<td><a href='#' onclick=\"showEditModal('modal1')\">" . "Edit" . "</a></td>";
只需将'modal1'的值更改为正确的元素ID。
答案 2 :(得分:0)
答案 3 :(得分:0)
将html与服务器语言分开,它将更具可读性
<div class="record-container">
<table class="table-record">
<tr>
<th>Title</th>
<th>Date Created</th>
<th>Control</th>
</tr>
<?php
$announcementDaoImpl = new AnnouncementDaoImpl($pdo);
$announcementList = $announcementDaoImpl->getAllAnnouncementByMostRecent();
foreach ($announcementList as $key => $value):
$announcementTitle = $value->getTitle();
$dateCreated = $value->getDateAdded();
/* comment: "<?=$var?>" this is equal to "echo $var;" endcomment */
?>
<tr>
<td><?= $announcementTitle ?></td>
<td><?= $dateCreated ?></td>";
<td>
<button onclick="showEditModal('<?=$your_variable?>')">
Edit
</button>
</td>
</tr>
<?php
endforeach;
?>
</table>
</div>