如何在 JavaScript 中正确转义 JavaScript?

发布于 2024-07-29 06:09:32 字数 286 浏览 2 评论 0原文

这可能是我不能做的事情,但是...

parent.document.getElementById('<?php echo $_GET['song']; ?>')
  .innerHTML = '<img src="heart.png" onmouseover="heartOver('');" >';

onmouseover="heartOver(''); 部分破坏了我的 JavaScript。有没有办法转义引号,以便我可以做到这一点?

This might be something I can't do but...

parent.document.getElementById('<?php echo $_GET['song']; ?>')
  .innerHTML = '<img src="heart.png" onmouseover="heartOver('');" >';

The onmouseover="heartOver(''); portion breaks my JavaScript. Is there a way to escape the quotes so I can do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你的往事 2024-08-05 06:09:32

这只是正确转义引号的问题。

parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML =
    '<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe">'
    + '<img src="images/heart.png" alt="Love!" onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';

此外,您还缺少 alt 属性的结束引号。

It's all just a matter of escaping the quotes properly.

parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML =
    '<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe">'
    + '<img src="images/heart.png" alt="Love!" onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';

Also you're missing and end quote for the alt attribute.

鲜血染红嫁衣 2024-08-05 06:09:32

使用反斜杠转义嵌套引号:\'

另外,从不在不验证或清理用户数据的情况下回显用户数据:

$song = $_GET['song'];

// Validate HTML id (http://www.w3.org/TR/REC-html40/types.html#type-name)
if(!preg_match('/^[a-z][-a-z0-9_:\.]*$/', $song) {
    // Display error because $song is invalid
}

或者

// Sanitize
$song = preg_replace('/(^[^a-z]*|[^-a-z0-9_:\.])/', '', $song);

Escape nested quotes with a backslash: \'

Also, never echo user data without validating or sanitizing it:

$song = $_GET['song'];

// Validate HTML id (http://www.w3.org/TR/REC-html40/types.html#type-name)
if(!preg_match('/^[a-z][-a-z0-9_:\.]*$/', $song) {
    // Display error because $song is invalid
}

OR

// Sanitize
$song = preg_replace('/(^[^a-z]*|[^-a-z0-9_:\.])/', '', $song);
<逆流佳人身旁 2024-08-05 06:09:32

您的问题是转义引号。 您可以通过将 ' 或 " 替换为 \' 或 '" 来转义单引号或双引号。

所以你的代码是:

parent.document.getElementById('').innerHTML = '

Your issue is with escaping quotes. You can escape either a single or double quote by replacing ' or " with \' or '".

So your code would be:

parent.document.getElementById('<?php echo $_GET['song']; ?>').innerHTML = '<a href="heart.php?action=unlove&song=<?php echo $song; ?>" target="hiddenframe"><img src="images/heart.png" alt="Love! onmouseover="heartOver(\'\');" width="16" height="16" border="0"></a>';

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文