如何在span标记中包装电子邮件地址

时间:2018-03-20 02:34:43

标签: javascript jquery

我有一个段落,内容是自动生成的,我无法直接编辑HTML。该段落将始终以电子邮件地址结束,然后是问号。我想加粗电子邮件地址。这是HTML:

<p class="unsub-main">Do you want to stop receiving emails from us to the email address noreply@noreply.com?</p>

我只想加粗电子邮件地址。我尝试了以下方法:

    $('.unsub-main:contains').html(function(){  
    // separate the text by spaces
    var text= $(this).text().split(' ');
    // drop the last word and store it in a variable
    var last = text.pop();
    // join the text back and if it has more than 1 word add the span tag
    // to the last word
    return text.join(" ") + (text.length > 0 ? ' <span class="last">'+last+'</span>' : last);   
});

我可以将最后一个字符串包装在span标记的段落中的问号之前吗?

2 个答案:

答案 0 :(得分:2)

您的代码几乎可以使用。您只需删除:contains选择器,该选择器仅用于过滤包含某些内容的元素。它的语法是$(":contains(text)"),但您没有在括号中定义要查找的文本,因此$('.unsub-main:contains')不匹配任何内容。删除:contains或将其与括号中的文字一起使用

$('.unsub-main').html(function(){  
    // separate the text by spaces
    var text = $(this).text().split(' ');
    // drop the last word and store it in a variable
    var last = text.pop();
    // join the text back and if it has more than 1 word add the span tag
    // to the last word
    return text.join(" ") + (text.length > 0 ? ' <span class="last">'+last+'</span>' : last);   
});
.last {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="unsub-main">Do you want to stop receiving emails from us to the email address noreply@noreply.com?</p>

答案 1 :(得分:0)

你不需要javascript,你甚至不需要CSS。你有什么理由不能把它包装成像这样的强标签吗?

<p class="unsub-main">Do you want to stop receiving emails from us to the email address <strong>noreply@noreply.com</strong>?</p>

或者更好的是,使用mailto:href和粗体显示电子邮件:

<p class="unsub-main">Do you want to stop receiving emails from us to the email address <strong><a href="mailto:noreply@noreply.com">noreply@noreply.com</a></strong>?</p>

简单的jquery方式:

var boldLink = '<p class="unsub-main">Do you want to stop receiving emails from us to the email address <strong><a href="mailto:noreply@noreply.com">noreply@noreply.com</a></strong>?</p>'
$('.unsub-main').html(boldLink)