来自 Javascript 的 MailTo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5265222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MailTo From Javascript
提问by Gordon Thompson
I've got a link button which is used to build up a mailto from the contents of the page. What is the best way to launch it from javascript without opening a blank window or disturbing the window it's called from?
我有一个链接按钮,用于从页面内容构建一个mailto。在不打开空白窗口或干扰调用它的窗口的情况下,从 javascript 启动它的最佳方法是什么?
function Email()
{
var sMailTo = "mailto:";
var sBody = "";
var alSelectedCheckboxes = new Array();
$("input:checkbox[CheckBoxType=Email]:checked").each(function()
{
alSelectedCheckboxes.push($(this).val());
});
if (alSelectedCheckboxes.length > 0)
{
for (var i=0; i<alSelectedCheckboxes.length; i++)
{
sBody += alSelectedCheckboxes[i];
sBody += "\n";
}
sMailTo += escape("<Insert Recipients Here>") +"?subject=" +escape("<Insert Subject Here>") +"&body=" +escape(sBody);
window.location.href = sMailTo;
}
else
{
alert("Please select some results");
}
}
The simple function is above. window.location.href doesn't work properly unless it's Firefox/Chrome (it redraws the page in IE8). I've also tried window.open(sMailTo, "_self") but again in IE8 this breaks the page that it's called from.
简单的功能如上。window.location.href 不能正常工作,除非它是 Firefox/Chrome(它在 IE8 中重绘页面)。我也试过 window.open(sMailTo, "_self") 但再次在 IE8 中这打破了它被调用的页面。
I'm sure this is a stupid question.... :-)
我确定这是一个愚蠢的问题....:-)
Thanks
谢谢
采纳答案by Groovetrain
I don't think it's stupid at all! This is a good start. What I'd try next is just to create an actual link object in jquery, append it to the body, and then click() it.
我觉得一点都不傻!这是一个好的开始。我接下来要尝试的只是在 jquery 中创建一个实际的链接对象,将其附加到正文,然后单击()它。
//window.location.href = sMailTo;
$('<a href="' + sMailTo + '">click</a>').appendTo('body').click().remove();
Should work as long as the escape() function you're using gets rid of all of the quotes and correctly encodes the html.
只要您使用的 escape() 函数去掉所有引号并正确编码 html,就应该可以工作。
But I have to say, this could be hard to get justright. If it still doesn't work, I'd recommend doing it server-side where the link POSTS all of the html needed.
但是,我不得不说,这可能是很难得到公正的权利。如果它仍然不起作用,我建议在服务器端进行,链接发布所有需要的 html。
回答by Kon
If you're using jQuery, then you can easily create an element based on the markup you build (refer to this answerfor an example) and then invoke the link's click event by simply doing this:
如果您使用的是 jQuery,那么您可以根据您构建的标记轻松创建一个元素(请参阅此答案的示例),然后通过简单地执行以下操作来调用链接的点击事件:
element.click();