質問

$('.email').each(function(l,i){
    var that = $(this);
    var thatOtherOne = $(this:after);
    $('<a>').attr('href', 'mailto: '+ that.html + thatOtherOne.css('content')).insertAfter(that);
    that.hide();
});
.email:after {
    content: "@mydomain.com";
}
<span class="email">info</span>

Hello again Stackoverflow!

This is my method against spam. Using CSS the :after selector and content I try fill my custom email in inside the <span> and the css adds the url. This doesn't make it clickable though, so that's why I try the above method using JS/jQuery.

This sadly doesn't work because $(this:after); is not a valid selector. How can I change this?

役に立ちましたか?

解決

You simply cannot construct a selector like that; it really doesn't make syntactic sense. Selectors are for searching through the DOM. To do what you're trying to do, you can try using the attr() trick in your "content":

.email:after {
  content: attr(data-domain);
}

Then in your markup:

  <a class=email data-domain='@whatever.com'>info</a>

And your JavaScript can then do this:

$('.email').each(function(l,i){
    var that = $(this);
    var domain = that.data('domain');
    $('<a>').prop('href', 'mailto: ' + that.text() + domain).insertAfter(that);
    that.hide();
});

The idea is to keep stuff that your code actually needs to use in a separate attribute, and then use the attr() operator (or whatever you want to call it) in the CSS rule to get that attribute value and use it as content. The operator can be combined with strings if you like. Chris Coyier has a good blog post about it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top