[英]Javascript popup only showing the last result in PHP query
我有以下代碼塊,我不知道如何做我想做的事情。
本質上我希望javascript彈出窗口顯示該行的值,但(顯然)它只顯示最后一行數據,因為沒有為每一行設置彈出窗口,而是在單擊時調用該變量。
任何幫助,將不勝感激!
<?php
$result = mysql_query("SELECT hr_overtime.overtime_id, hr_user.name, hr_overtime.overtime_date, hr_overtime.overtime_type, hr_overtime.overtime_from, hr_overtime.overtime_to, hr_overtime.overtime_amount, hr_overtime.details
FROM hr_overtime
inner join hr_user
on hr_user.user_id = hr_overtime.user_id
where hr_overtime.overtime_status = 'Pending' order by hr_overtime.overtime_date ASC");
echo "
<table border='0'>
<tr>
<th class='tablecell_header'>Consultant</th>
<th class='tablecell_header'>Date</th>
<th class='tablecell_header'>Type</th>
<th class='tablecell_header'>From</th>
<th class='tablecell_header'>To</th>
<th class='tablecell_header'>Amount</th>
<th> </th>
<th> </th>
<th> </th>
</tr>";
while($row = mysql_fetch_array($result))
{
$work = $row['details'];
echo "<tr>";
echo "<td class='tablecell'>" . $row['name'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_date'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_type'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_from'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_to'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_amount'] . "</td>";?>
<td class='tablecell'> <button onclick="myFunction()">Show work</button> </td><script>
function myFunction()
{
alert("<?php echo $work;?>");
}
</script>
<?php
echo "<td valign='middle'><form action='manager_overtime_approve.php' method='post'>
<input name='approve_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='APPROVE' id='edit' />
</form></td>";
echo "<td valign='middle'><form action='manager_overtime_reject.php' method='post'>
<input name='cancel_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='REJECT' id='edit' />
</form></td>";
echo "</tr>";
}
echo "</table>";
?>
您不需要使用錯誤的單獨功能。 您可以簡單地使用內聯警報:
<td class='tablecell'> <button onclick="alert('<?php echo $work;?>');">Show work</button>
你不能在你的foreach循環中插入myFunction()
的聲明,這樣你就可以覆蓋行為所顯示的每個條目,因此它只適用於最后一行。
一個快速的解決方案是將整個$ work變量作為onclick函數的參數插入,例如。
<td class='tablecell'> <button onclick="myFunction('<?php echo $work ?>')">Show work</button>
然后在foreach循環之外,您可以定義myFunction
例如:
function myFunction(details){
alert(details)
}
我認為,在結果HTML中,你有myFunction()的多個定義,而javascript只使用最后一個。 您可以使用HTML標記屬性來顯示正確的信息。
嘗試這個
$work .= $row['details'];
並將javascript設置為循環
祝好運
這是因為myFunction
是一個JavaScript函數,它被定義一次 ,並沒有按不共享相同的范圍,因為PHP。 所以$work
只保留最后一個值。
我建議這樣的事情:
echo "<tr data-detail-value='$work'>";
...
<td class='tablecell'> <button onclick="myFunction(this)">Show work</button>
...
function myFunction(btn) {
alert(btn.parentNode.parentNode.getAttribute("data-detail-value"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.