在jQuery中查找文本字符串,并将其设置为粗体 [英] Find text string in jQuery and make it bold
本文介绍了在jQuery中查找文本字符串,并将其设置为粗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做的是使用jQuery来查找段落中的一段文本,并添加一些CSS使其变粗体。我似乎不明白为什么这将无法工作:
What I want to do is use jQuery to find a piece of text within a paragraph and add some CSS to make it bold. I can't seem to figure out why this won't work:
$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
});
about_theresidency中的文本被动态拉入,因此我在窗口加载后执行。
The text in "about_theresidency" is dynamically pulled in, hence me executing it after the window has loaded.
推荐答案
您可以使用 replace()
> html():
You can use replace()
with html()
:
var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
编辑:http://jsbin.com/AvUcElo/1/edit
我把它变成了一个lil的插件,在这里:
I turned it into a lil' plugin, here:
$.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']
});
这篇关于在jQuery中查找文本字符串,并将其设置为粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文