PHP - 回显 HTML 的多个嵌套引号

PHP - Echoing multiple nested quotes of HTML

我试图通过 PHP

回应 HTML 的以下行
echo "<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass('$id', '$formattedDate', '$time')'></a><p class='text-center'>".$formattedDate." @ $time</p>";

我没有收到错误。但是 onClick='cancelClass... 的引号没有被正确解析,这导致 javascript 函数没有执行。

如何在 Google Chrome 源视图中进行颜色编码

如何对其进行颜色编码(另一个函数的示例)

改为如下

echo "<a class=\"fa fa-ban fa-2x cancelClass\" onClick=\"cancelClass('$id', '$formattedDate', '$time')\"></a><p class=\"text-center\">".$formattedDate." @ $time</p>";

转义属性双引号你可以有一个规范化的 html

您需要执行以下操作:

echo "<a class='fa fa-ban fa-2x cancelClass' onClick=\"cancelClass('".$id."', '".$formattedDate."', '".$time."')\"></a><p class='text-center'>".$formattedDate." @ $time</p>";

它们 确实 得到了正确的解析,但是您指定了错误的使用。 Javascript 无法区分包裹字符串变量的引号和包裹 "onclick" 值的引号,它认为 onclick 结束得太早。

为了区分它们,你必须避开它们。使用 \" 表示括号内的那些。

echo "<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass(\"$id\", \"$formattedDate\", \"$time\")'></a><p class='text-center'>".$formattedDate." @ $time</p>";

应该可以解决问题。

或者,不要对整个字符串使用 echo,只需直接输出大部分即可:

?> //temporarily stop interpreting the file as PHP, so the next bit will be output directly as raw HTML
<a class='fa fa-ban fa-2x cancelClass' onClick='cancelClass("<?php echo $id;?>", "<?php echo $formattedDate; ?>", "<?php echo $time;?>")'></a><p class='text-center'>".$formattedDate." @ $time</p>
<?php //continue with PHP

在 HTML 中使用双引号。 使用带有 ENT_QUOTES 的 htmlspecialchars 转义具有双引号的值。

echo '<a class="fa fa-ban fa-2x cancelClass" onClick="'.htmlspecialchars("cancelClass('$id', '$formattedDate', '$time')", ENT_QUOTES).
 '"></a><p class="text-center">'.$formattedDate." @ $time</p>";