小编典典

在jQuery中查找文本字符串并使其加粗

css

我想做的是使用jQuery在一个段落中查找一段文本并添加一些CSS以使其变为粗体。我似乎无法弄清楚为什么这行不通:

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

动态地提取“ about_theresidency”中的文本,因此在加载窗口后执行该文本。


阅读 418

收藏
2020-05-16

共1个答案

小编典典

你可以用replace()html()

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

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

$.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']
});
2020-05-16