jQuery mailto with anchor element

馋奶兔 提交于 2019-12-21 18:33:39

问题


I tried this with umpteen examples we see on the net. But I guess there is none that is simple and works on all browsers (IE 8 and above as well).

I am trying to simply open up Outlook window with mailto link.

<a href="#" name="emailLink" id="emailLink">Email</a>

JQuery:

$(function () {
  $('#emailLink').on('click', function (event) {
    alert("Huh");
    var email = 'test@theearth.com';
    var subject = 'Circle Around';
    var emailBody = 'Some blah';
    window.location = 'mailto:' + email + '?subject=' + subject + '&body=' +   emailBody;
  });
});

Granted, I am a jQuery newbie. The above just doesn't work. It just flickers the browser but nothing opens. I guess this is because of window.location.

Is there a simple solution? I want this to work in IE8 & above and in all browsers.

The body is generated automatically (in JSP).


回答1:


here's working solution:

<a href="#" name="emailLink" id="emailLink">Email</a>

and the function:

$(function () {
  $('#emailLink').on('click', function (event) {
      event.preventDefault();
    alert("Huh");
    var email = 'test@theearth.com';
    var subject = 'Circle Around';
    var emailBody = 'Some blah';
    window.location = 'mailto:' + email + '?subject=' + subject + '&body=' +   emailBody;
  });
});



回答2:


$(function () {
  $('[name=emailLink]').click(function () {
    var email = 'test@theearth.com';
    var subject = 'Circle Around';
    var emailBody = 'Some blah';
    $(this).attr('href', 'mailto:' + email +
           '?subject=' + subject + '&body=' +   emailBody);
  });
});

.click can be replaced with .mousedown and so on.. or just

$(function () {
  $('[name=emailLink]').each(function() {
    var email = 'test@theearth.com';
    var subject = 'Circle Around';
    var emailBody = 'Some blah';
    $(this).attr('href', 'mailto:' + email +
           '?subject=' + subject + '&body=' +   emailBody);
  });
});



回答3:


If you do not need the address as a text anywhere on the website I would suggest this:

$('a[data-mail]').on('click', function() {
   window.location = 'mailto:' + $(this).data('mail')+'@yourdomain.net' + '?subject=Spotflow';
});

The link woud look like this:

<a href="#" data-mail="max">Send me a mail</a>

No chance for bots!




回答4:


Your selector is looking for an ID

$('#emailLink')

But you have only specified the name.

Add id="emaillink" to the anchor tag.




回答5:


You don't need any javascript/jQuery at all for this, just the following HTML should do:

<a href="mailto:test@theearth.com?subject=Circle Around&body=Some blah" name="emailLink">Email</a>


来源:https://stackoverflow.com/questions/26104378/jquery-mailto-with-anchor-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!