首页 > 解决方案 > 如何避免 HTML javascript 字符串间距带有 (+) 符号?

问题描述

我已经创建了一个带有 javascript 的 html 表单,它必须在 IE 上运行才能通过使用 mailto 操作触发 Outlook,但是对于我传递给 Outlook 的字符串,所有间距都自动替换为 (+) 符号。下面是我的代码:

<script>
var i= 'Product name:';
var idproduct=i.split('+').join(' ')
    function beforeSubmit() {

        var Product = document.getElementById("Product_Name");
        var Email = document.getElementById("Email_Address");
        var body = document.getElementById("body");
        body.value = idproduct+ Product.value +"\n";
      }
</script>
<input name="Subject" size="78" id="Subject" type="hidden" value=" Car Notification" /><br/>

但我得到的输出是:

邮件主题:

Car+Notification

电子邮件正文:

Product+name:Honda

我的预期输出没有空格的所有加号。有人对这个问题有想法吗?

标签: javascripthtmlinternet-explorer

解决方案


我们可以像这样编写 mailto 链接来避免“+”符号:mailto:somebody?subject=etc&body=etc。我们将主题和正文作为查询参数发送。您可以查看下面的示例,它适用于 IE:

function beforeSubmit() {
  var Product = document.getElementById("Product_Name").value;
  var Email = document.getElementById("Email_Address").value;
  var eTo = encodeURI(Email);
  var eSubj = encodeURI("Car Notification");
  var eBody = encodeURI(Product + "\n" + "anotherline");
  var email = "mailto:" + eTo + "?subject=" + eSubj + "&body=" + eBody;
  document.getElementById("myform").href = email;
}
<form>
  <input id="Email_Address" type="text" value="somebody@example.com" />
  <input id="Product_Name" type="text" value="enter your message here" />
  <a href="" id="myform" onclick="beforeSubmit()"><input type="button" value="submit" /></a>
</form>


推荐阅读