编写此页面我从数据库中获取值,然后使用PHP创建页面。它有一个带有onclick =“colorRed('line1')的按钮的列。我无法想象如何正确地转义这个以使函数调用工作。如果我在PHP表单构建之外做它可以正常工作所以我确信这是我构建文件的方式。请看看并给我任何建议。这是PHP部分的代码snippit:
echo "<form name=\"form1\" action=\"save_special_announcement.php\" method=\"post\">";
echo "Line 1: <input id=\"line1\" size=\"39\" maxlength=\"38\" type=\"text\" value=\"" .$row['line1']. "\"/>
<input type=\"button\" onclick=\"colorRed('line1')\" name=\"button1\" value=\"Red\">";
这是简单的函数colorRed()调用(显然它将文本更改为红色):
function colorRed(input) { // Change text to red
document.getElementById(input).style.color = 'red'; };
谢谢你的帮助!
答案 0 :(得分:2)
首先,如果你用单引号括起你的字符串,你会更高兴,因为那样你就不需要逃避所有那些双打,你的任务会自动更简单:
echo '<form name="form1" action="save_special_announcement.php" method="post">';
echo 'Line 1: <input id="line1" size="39" maxlength="38" type="text" value="' . $row['line1'] . '"/>';
echo '<input type="button" onclick="colorRed('line1')" name="button1" value="Red">';
当然,您会注意到最后一行仍未正确转义。但现在它更简单了。你只需要像这样转义单引号:
echo '<input type="button" onclick="colorRed(\'line1\')" name="button1" value="Red">';
作为奖励,以下是关于echo
的提示:仅使用一个echo
语句并使用,
代替.
,以获得更好的效果:
echo '<form name="form1" action="save_special_announcement.php" method="post">',
'Line 1: <input id="line1" size="39" maxlength="38" type="text" value="', $row['line1'], '"/>',
'<input type="button" onclick="colorRed(\'line1\')" name="button1" value="Red">';
此外,如果您尚未这样做,请确保$row['line1']
的值已正确编码(使用htmlspecialchars()
)。如果它包含&符号,双引号或其他一些字符并且未编码,则会遇到问题。