【问题标题】:\n not working in Javascript [duplicate]\n 不能在 Javascript 中工作 [重复]
【发布时间】:2014-06-02 05:32:09
【问题描述】:

由于某种原因,\n 在 javascript 中不适合我。无论如何要修复它或使用html?就我而言,我认为在我的href 中使用<br> 将不起作用。你有什么建议。

工作 JSFiddle here.

HTML:

<a id = 'emailoff' href = "" target = "_blank">
    <div id= "btn1">
        <h2 id = "enter">Send Email</h2>
    </div>
</a>

Javascript:

$('#btn1').click(function() {
    $("#emailoff").attr("href", "mailto:" +
        "?subject=Your ThinOptics glasses" +
        "&body=To get your new ThinOptics glasses simply click this link and pick the case and color you like best.  You'll get  free shipping on your order. \n"+
        " WWw.Thinoptics.Com/teddy@shalon.com \n" +
        "\n Enjoy")
});

【问题讨论】:

  • \n 在 JavaScript 中确实有效。但是您的问题是 href 得到多线您正确想要的是转义新行,以便邮件客户端获得\n 并可以将其视为\n:TLDR:使用\\n,但支持可能因客户端而异客户。
  • 这可能会回答你的问题stackoverflow.com/questions/1155678/…
  • @NULL "\\n" 似乎不起作用...您的意思是用“\\n”替换“\n”吗?
  • 你没有在你的href中动态插入任何东西,那么为什么不在渲染页面时插入href属性呢?
  • @JonathanAnctil 成功了!谢谢!!

标签: javascript jquery html


【解决方案1】:

试试

<br>

而不是

 \n

\n 在 html 中呈现为 1 个空格,\t 或 \s

也是如此

【讨论】:

  • 这不适用于基于文本的电子邮件客户端
  • 它适用于 %0D 而不是 \n
  • 实际上这根本行不通,因为the specification for mailto 说它只能用于基于文本的电子邮件,因此,
    将按原样呈现,而不是作为换行符. The "body" hname should contain the content for the first text/plain body part of the message.
【解决方案2】:

您必须对新行进行 URL 编码。编码后的新行应该是%0Ahttp://jsfiddle.net/mendesjuan/LSUAh/

<a id = 'emailoff' href = "mailto:me@you.com?subject=hello&body=a%0Ab" target = "_blank">
    <div id= "btn1">
        <h2 id = "enter">Send Email</h2>
    </div>
</a>

如果你是用 JS 做的,使用下面的

$('#btn1').click(function() {
    $("#emailoff").attr("href", "mailto:" +
        "?subject=Your ThinOptics glasses" +
        "&body=To get your new ThinOptics glasses simply click this link and pick the case and color you like best.  You'll get  free shipping on your order. %0A"+
         " WWw.Thinoptics.Com/teddy@shalon.com  %0A" +
        " %0A Enjoy")
});

请注意,您不必对 URL 编码版本进行硬编码,您可以使用

encodeURIComponent("\n") // %0A

附:不依赖正在配置的用户邮件客户端不是更好吗?改为使用您自己的服务器发送电子邮件,以确保所有用户都可以发送消息。

【讨论】:

  • 这是正确的做法。我可以看到春假已经准备好让我放慢速度:)
  • 我还有一个小问题......如果我想将网址放在该网址的超链接中,我该怎么做?由于某种原因,该链接不起作用...
  • @LiamShalon 请创建一个单独的问题。在 SO,我们喜欢关于单一事物的问题。这样,这个问题对其他人更有用。随意在这里链接到它并在上面标记我,以便我收到通知。我想我知道答案,但是当您创建一个新问题来展示您的尝试时会容易得多。
猜你喜欢
  • 2019-06-08
  • 2015-10-07
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 2011-09-25
  • 1970-01-01
相关资源
最近更新 更多