问题描述
创建字符串后,我试图突出显示"字符串中的特定单词.
I am trying to "highlight" specific words in a string after the string has been created.
我目前正在这样做:
var keywords = [
"Monday",
"monday",
"Tuesday",
"tuesday",
"Wednesday",
"wednesday",
"Thursday",
"thursday",
"Friday",
"friday",
"Saturday",
"saturday",
"Sunday",
"sunday"
];
function highlightImportant(that) {
that.find('.email-container').each(function(){
var full_text = $(this).text();
$.each(keywords, function(i){
full_text = full_text.replace(keywords[i], "<b>"+keywords[i]+"</b>");
$(this).text(full_text);
});
});
}
此函数在此结尾处调用:
this function is called at the end of this:
function getEmails(email, name) {
console.log("working...");
$('.contact--details__show__emails').empty();
$.post('php/contacts-get-email.php', {email:email}, function(data) {
var email_body = data.split("<:>");
$.each(email_body.reverse(), function(i){
if(email_body[i]) {
var direction = email_body[i].split(':dir:')[0];
var email_text = email_body[i].split(':dir:')[1].split(':date:')[0];
var email_date = email_body[i].split(':dir:')[1].split(':date:')[1];
var d = new Date(0);
d.setUTCSeconds(email_date);
if(direction === "TO"){
var initial = "Us";
} else {
var initial = name;
}
var email_block = $('<div class="emailBlock dir-'+direction+'" style="opacity:0;">\
<div class="avatar">'+ initial +'</div>\
<div class="email-container">'+email_text+'</div>\
<div class="date">'+d+'</div>\
</div>');
$('.contact--details__show__emails').append(email_block);
email_block.delay(100*i).animate({"opacity":"1"}, 500);
highlightImportant($('.contact--details__show__emails'));
}
});
});
}
这似乎应该起作用,当我console.log
事件时,我看到它遍历每个容器的每个关键字,但似乎即使它们存在,也找不到关键字.
This seems like it should work, and when I console.log
the event, I see it running through each keyword for every container, but it seems it's not finding the keywords even when they exist.
我想看到的是当我有这样的字符串时:
What I'd like to see happen is when I have a string like this:
var string = "Let's meet Monday or Tuesday";
我想让它们变粗体,像这样:
I'd like to have them turn bold, like so:
让我们见面星期一或星期二"
有什么想法吗?
推荐答案
此行有两个错误:
$(this).text(full_text);
1)this
指向字符串而不是DOM元素,并且2)如果要将标记放入元素中,则应使用html()
方法.
1) this
points to string rather to DOM element and 2) you should use html()
method if you want markup to go into element.
并且您使用的String.replace()
格式将仅替换第一个条目,因此您应该执行以下操作:
And String.replace()
in that form you use will replace only first entry, so you should do this:
that.find('.email-container').each(function(){
var full_text = $(this).text();
$.each(keywords, function(i) {
full_text = full_text.replace(new RegExp(keywords[i],"gi"), "<b>"+keywords[i]+"</b>");
});
$(this).html(full_text);
});
这篇关于jQuery替换字符串中的单词数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!