如果我嘗試將PHP數組元素作爲參數傳遞,我無法調用Javascript函數。 我試過所有的東西(除了正確的東西,我想)。無法將PHP變量傳遞給javascript函數
這裏是PHP代碼 - 第二行是發生故障的一個:
var_dump($theRow[11]);
$htmlBuffer = '<div onclick="showIt(' . $theRow[11] . ')">does not work!</div>';
$htmlBuffer = $htmlBuffer . '<div onclick="showIt()"> THIS WORKS FINE! </div>';
下面是HTML代碼,以輸出上述:
<html>
<body>
<?php echo '<div id="listSection">' . $htmlBuffer . '</div>';
?>
</body>
</html>
這裏是javascript函數'showIt()':
function showIt(theVal)
{
alert("HERE IS WHAT WAS PASSED IN: " + theVal);
}
這裏是頁面上的輸出:
1)首先,我看到這個頁面上:
string(8) "52e43c33"
現在,這是100%的罰款。這是我期望在陣列位置#11看到的。 請注意'theRow [11]'是一個PHP數組,其中每個數組元素是一個8位數(十六進制)的數字。並且該var_dump()調用顯示位置11處的數組元素是有效的8位數字(十六進制),這就是我期望在那裏找到的。所以沒關係。
2)然後,我看到這個頁面上:
does not work!
THIS WORKS FINE!
當我點擊 「這工作得很好!」在我的網頁上,我看到一個警告框出現這樣說:
HERE IS WHAT WAS PASSED IN: undefined
現在,這對我來說沒問題。我沒有將一個參數傳遞給我點擊的代碼行showIt()。 alert()框出現的事實顯示了onclick()正在工作的100%確定性。
,這裏是失敗的原因:當我點擊文本的瀏覽器窗口中的行:
**does not work!**
- 這是試圖通過theRow [11]作爲參數showIt() - 在showIt()中沒有出現提示框。
我想「好吧,這是一個引用問題。」
所以我嘗試了這些無濟於事:這裏成功MY引用嘗試
$htmlBuffer = '<div onclick="showIt(\'' . $theRow[11] . '\')">does not work!</div>';
$htmlBuffer = '<div onclick="showIt(\"' . $theRow[11] . '\")">does not work!</div>';
$htmlBuffer = '<div onclick="showIt("' . $theRow[11] . '")">does not work!</div>';
$htmlBuffer = '<div onclick="showIt($theRow[11])">does not work!</div>';
NONE。
如何正確引用的代碼行:)
$htmlBuffer = '<div onclick="showIt(' . $theRow[11] . ')">does not work!</div>';
得到theRow [11]成功傳遞到showIt(?
編輯:這裏是頁面的「查看源代碼」:
string(8) "7ab79992"
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function showIt(theVal)
{
alert("HERE IS WHAT WAS PASSED IN: " + theVal);
}
</script>
</head>
<body>
<div id="listSection"><div onclick="showIt(7ab79992)">does not work!</div>
<div onclick="showIt()"> THIS WORKS FINE! </div></div>
</body>
</html>
你能發佈生成的html代碼(不是屏幕輸出)嗎? –
打開javascript調試器,看看是否有錯誤。 – Aris
@KristenJukowski我在原始問題的末尾添加了「查看源代碼」輸出。 – CFHcoder