您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

你可以用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']
});
JS 2022/1/1 18:19:22 有337人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶