this:after selector jQuery

this:after selector jQuery

本文关键字:jQuery selector after this      更新时间:2023-09-26
$('.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>

你好,再次堆栈溢出!

这是我对付垃圾邮件的方法。使用 CSS :after选择器,content我尝试在<span>中填写我的自定义电子邮件,CSS 会添加 URL。这并不能使它可点击,所以这就是为什么我使用 JS/jQuery 尝试上述方法的原因。

遗憾的是,这不起作用,因为$(this:after);不是有效的选择器。我该如何更改此设置?

你根本无法构造这样的选择器;它真的没有语法意义。选择器用于搜索 DOM。 要执行您要执行的操作,您可以尝试在"内容"中使用attr()技巧:

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

然后在您的标记中:

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

然后你的 JavaScript 可以做到这一点:

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

这个想法是将代码实际需要使用的内容保留在单独的属性中,然后在 CSS 规则中使用 attr() 运算符(或任何您想要调用它的内容(来获取该属性值并将其用作内容。如果需要,运算符可以与字符串组合。克里斯·科耶尔(Chris Coyier(有一篇很好的博客文章。