gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:55:51 24 4
gpt4 key购买 nike

我使用 PHP 输出多行信息。我试图向每一行添加隐藏/显示。我“ID”该行,然后添加一个简单的文本“隐藏/显示”按钮,该按钮引用 ID 的行并尝试切换“显示”属性。

我尝试转义引号,将其更改为单引号,添加/删除括号。我不知所措。

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>";

意外的 token “}”

最佳答案

你的 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>

在我看来,第一个选项看起来更整洁,特别是如果您考虑需要转义反斜杠 (\)。所以你的固定代码是

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 的一部分。

关于javascript - 为什么我在这行代码上不断收到 "unexpected token"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56589154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com