在 JavaScript 中逃脱

Escaping in JavaScript

我该如何进行这项工作? <a href='javascript:func("Jack'S Birthday")'>Jack's Birthday</a>

如果可以,就这样

<html>
  <header>
    <script>
    function func(x) {
      alert(x);
    }</script>
  </header>
  <body>
    <a href="javascript:func('Norman\'S Birthday')">Birthday</a>
  </body>
</html>

转换为 NCR。这应该有效。

<html>
    <a href='javascript:func("Norman&#39;S Birthday")'>Birthday</a>
</html>

或者。

<html>
    <a href='javascript:func("Norman&#x27;S Birthday")'>Birthday</a>
</html>

Do as follows:

// How about using variables instead?
var emily = "Emily'S Birthday"
var birthdays = {
  john: "John'S Birthday"
}

function func(val) {
  console.log(val);
}
<!DOCTYPE html>
<html>

<body>
  <a href='javascript:func("Jack&apos;S Birthday")'>Jack's Birthday</a>
  <br>
  <a href="javascript:func('Norman\'S Birthday')">Norman's Birthday</a>
  <br>
  <a href="javascript:func(emily)">Emily's Birthday</a>
  <br>
  <a href="javascript:func(birthdays.john)">John's Birthday</a>
</body>

</html>

Explanation:

  1. 使用反斜杠转义时,将单引号放在双引号内 \
  2. 当你使用 $apos;
  3. 时,在单引号内使用双引号
  4. 最重要的是,使用变量,它们可以减轻很多痛苦 -

    一个。您不必进入 html 来修改值,
    b.这些可以在一个地方或单个文件中声明,
    C。它们可以从 back-end
    中获取 d.最好的是,无需处理引号!

显然您无法转义 HTML 属性中的字符。正确的方法是使用 HTML 实体,例如 &apos;

<a href='javascript:console.log("&apos;")'>click me</a>

参见How to properly escape quotes inside html attributes?