我正在尝试创建mailto按钮,在该按钮中创建电子邮件的标题和正文。
我的代码正确地完成了它的工作,但我意识到这封信是'&'在文本中,然后跳过其余的代码。所以字符串在'&'之前是可见的,之后的任何内容都不会出现在电子邮件正文中。
查看示例:jsFiddle
var title = "my track title";
var artist= "ArtistA & Artist B";
var trackURL= " http://localhost/music";
var subjectText = title + " by " + artist;
var bodyText = "Check out the track " + title + " by " + artist + " on " + trackURL;
var url = 'mailto:' + '' + '?subject=' + subjectText + '&body=' + bodyText;
$(".email").on("click tap", function(event) {
event.preventDefault();
window.location = url;
});
console.log(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="email">Send Email</button>
在控制台中显示正确但如果您按下按钮并在电子邮件应用程序中打开它,您会看到文本如下:Check out the track my track title by ArtistA
,其余部分丢失。
如果我改变'&amp;' '和'它正常工作并显示:Check out the track my track title by ArtistA and Artist B on http:/localhost/music
知道怎么解决吗?我试过.toString()
但是没有用。
答案 0 :(得分:1)
这是因为&
是url参数的分隔符。
在将这些值添加到网址字符串之前,您需要对值进行编码( encodeURIComponent
用于文本,encodeURI
用于网址)。
var title ="my track title";
var artist= "ArtistA & Artist B";
var trackURL= " http://localhost/music";
var subjectText = encodeURIComponent(title + " by " + artist);
var bodyText = encodeURIComponent("Check out the track " + title + " by " + artist + " on ") + encodeURI(trackURL);
var url = 'mailto:' + '' + '?subject=' + subjectText + '&body=' + bodyText;
$(".email").on("click tap", function(event) {
event.preventDefault();
window.location = url;
});
console.log(url);