为什么我在这行代码中不断收到 "unexpected token" 错误?

Why I keep getting an "unexpected token" error on this line of code?

我正在使用 PHP 输出信息行。我正在尝试向每一行添加 hide/show。我 "ID" 该行,然后添加了一个引用 ID 行的简单文本 "Hide/Show" 按钮,并尝试切换 "display" 属性。

我试过转义引号,将它们更改为单引号,adding/removing 括号。我很茫然。

echo "<table width=\"640\" style=\"margin-left: auto; margin-right: auto;\"><tr id=\"JEntry".$data['ID']."\" style=\"display: visible\"><td><button onmousedown=\"javascript: if (document.getElementById(\"JEntry".$data['ID']."\").style.display != \"visible\") { document.getElementById(\"JEntry".$data['ID']."\").style.display = \"visible\"; } else { document.getElementById(\"JEntry".$data['ID']."\").style.display = \"none\"; }\">Hide or Show</button>";

意外的令牌“}”

您的 PHP 代码没问题。但是,生成的 HTML 需要对其属性进行转义。

例如,您的代码输出类似于

<button onmousedown="javascript: if (document.getElementById("JEntry")) {}"></button>

如您所见,javascript 中的引号与属性值的引号匹配。这将导致解析问题。

要解决此问题,请仅在 javascript

中使用单引号
<button onmousedown="javascript: if (document.getElementById('JEntry')) {}"></button>

或者逃避他们。

<button onmousedown="javascript: if (document.getElementById(\"JEntry\")) {}"></button>

在我看来,第一个选项看起来更整洁,尤其是当您考虑需要转义 back-slashes (\) 时。所以你的固定代码是

echo "<table width=\"640\" style=\"margin-left: auto; margin-right: auto;\"><tr id=\"JEntry".$data['ID']."\" style=\"display: visible\"><td><button onmousedown=\"javascript: if (document.getElementById('JEntry".$data['ID']."').style.display != 'visible') { document.getElementById('JEntry".$data['ID']."').style.display = 'visible'; } else { document.getElementById('JEntry".$data['ID']."').style.display = 'none'; }\">Hide or Show</button>";

阅读本文的方法是未转义双引号 (") 是 PHP 的一部分,转义双引号 (\") 是 HTML 的一部分,和 JS 的单引号 (') 部分。