在jQuery中查找文本string,并将其设置为粗体

我想要做的就是使用jQuery在一个段落中find一段文字,并添加一些CSS使其变为粗体。 我似乎无法弄清楚为什么这不起作用:

$(window).load(function() { // ADD BOLD ELEMENTS $('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'}); }); 

“about_theresidency”中的文本被dynamic拉入,因此我在窗口加载后执行它。

你可以用html()来使用replace() html()

 var html = $('p').html(); $('p').html(html.replace(/world/gi, '<strong>$&</strong>')); 

编辑: http : //jsbin.com/AvUcElo/1/edit

我把它变成了一个小插件,在这里:

 $.fn.wrapInTag = function(opts) { var tag = opts.tag || 'strong' , words = opts.words || [] , regex = RegExp(words.join('|'), 'gi') // case insensitive , replacement = '<'+ tag +'>$&</'+ tag +'>'; return this.html(function() { return $(this).text().replace(regex, replacement); }); }; // Usage $('p').wrapInTag({ tag: 'em', words: ['world', 'red'] }); 

我有一个类似的问题,并尝试使用elclanrs提出的解决scheme。 它的效果很好,但只有当你想改变的文本中没有html元素。 如果文本内有标签,运行wrapInTag函数后会丢失。

这里是我的问题的内部节点友好的解决scheme(我包括了我用来编写代码的资源的链接)。

 // http://stackoverflow.com/a/9795091 $.fn.wrapInTag = function (opts) { // http://stackoverflow.com/a/1646618 function getText(obj) { return obj.textContent ? obj.textContent : obj.innerText; } var tag = opts.tag || 'strong', words = opts.words || [], regex = RegExp(words.join('|'), 'gi'), replacement = '<' + tag + '>$&</' + tag + '>'; // http://stackoverflow.com/a/298758 $(this).contents().each(function () { if (this.nodeType === 3) //Node.TEXT_NODE { // http://stackoverflow.com/a/7698745 $(this).replaceWith(getText(this).replace(regex, replacement)); } else if (!opts.ignoreChildNodes) { $(this).wrapInTag(opts); } }); }; 

例如: http : //jsbin.com/hawog/1/edit

尝试:

 $(window).load(function() { // ADD BOLD ELEMENTS $('#about_theresidency:contains("cross genre")').each(function(){ $(this).html( $(this).html().replace(/cross genre/g,'<strong>$&</strong>') ); }); }); 

需要一个更安全的方法,可以逃脱。 这是一个香草的解决scheme

 var str = 'The world is big <b onclick="alert(false)">world</b> red. the world is also small' var words = ['world', 'is'] var reg = RegExp(words.join('|'), 'gi') var p = document.createElement('p') p.innerText = str p.innerHTML = p.innerHTML.replace(reg, '<u>$&</u>') document.body.appendChild(p) console.log(p.outerHTML)