【问题标题】:Javascript quitting on an ampersand "&"Javascript 在 & 符号上退出
【发布时间】:2011-06-16 19:26:45
【问题描述】:

我正在尝试使用此 JS 在客户端计算机上打开一封新电子邮件,其中页面标题已填充在主题行和正文中,通过此链接调用 <a href="javascript:mailpage()">Email</a>

function mailpage()
{ mail_str = "mailto:?subject= " + document.title; mail_str += 
"&body=Hi, I thought you might be interested in this: " 
+ document.title; mail_str += 
". You can check out the web site at "
+ location.href; location.href = mail_str;
}

但是我的一些页面在页面标题中有一个 & 符号,并且该功能会阻塞,并且只在 & 之前插入文本,而不是 & 或之后的任何内容。 (是的,“扼流圈”是一个技术含量很高的术语。)

有没有办法逃脱 & 让 JS 不会窒息? & 实际上在页面源中显示为@。还是我需要去一个 php 函数?谢谢。

编辑:这可行: + encodeURIComponent(document.title); mail_str +=

【问题讨论】:

  • 它适用于我。您可以尝试将 & 更改为 &不过。
  • 您可以尝试对 document.title 进行 urlencode 吗? (不确定电子邮件客户端是否会正确解码它......)

标签: javascript html escaping ampersand


【解决方案1】:

您应该在目标中插入的那些变量上调用encodeURIencodeURIComponent。这将消除犯规角色并让它通过。

function mailpage()
{
    var subject = encodeURIComponent(document.title),
        body= encodeURIComponent("Hi, I thought you might be interested in this: "
            + document.title + ". You can check out the web site at "
            + location.href;

    location.href = "mailto:?subject= " +subject + "&body=" + body;
}

【讨论】:

    【解决方案2】:
    encodeURIComponent(document.title)
    

    【讨论】:

      【解决方案3】:
      function mailpage()
      { mail_str = "mailto:?subject= " + document.title; mail_str += 
        "\&body=Hi, I thought you might be interested in this: " 
        + document.title; mail_str += 
        ". You can check out the web site at "
        + location.href; location.href = mail_str;
      }
      

      在javascript中使用\作为转义字符

      【讨论】:

      • 问题与JS转义无关,与HTML标签属性中的HTML实体转义有关。
      • 明白了。开始我的回答 b4 我完全读完了这个问题……我的错。为你重新标记问题。
      猜你喜欢
      • 1970-01-01
      • 2020-01-22
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 2013-09-27
      相关资源
      最近更新 更多