在jQuery中查找文本字符串并使其变为粗体

Mic*_*ael 26 css jquery html5

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

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

"about_theresidency"中的文本被动态拉入,因此我在窗口加载后执行它.

elc*_*nrs 82

你可以用replace()html():

var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
Run Code Online (Sandbox Code Playgroud)

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

我把它变成了一个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']
});
Run Code Online (Sandbox Code Playgroud)

  • 请参阅编辑,现在您可以随时随地使用. (3认同)
  • 你的解决方案有效,但打破内部标签(如果你改变的元素内部有任何内容),所以我冒昧地修改它并将其作为替代答案发布. (3认同)
  • 我希望我能给出这个答案10个赞成票.我喜欢它. (2认同)

jah*_*ahu 14

我有类似的问题,并尝试使用elclanrs提出的解决方案.它工作得很好,但前提是你想要改变的文本中没有html元素.如果文本中有任何标记,则在运行该wrapInTag函数后它们将丢失.

这是我对内部节点友好的解决方案(我包含了用于编写代码的资源的链接).

// 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);
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢!这太棒了。我发现这与部分单词匹配-因此,如果您传递“单词”,它将与“单词”和“剑”匹配。我为RegExp更新了以下代码:`regex = RegExp('(^ | \\ s)'+ words.join('(\\ s | $)|(^ | \\ s)')+'( \\ s | $)','gi'),`这将仅与以空格为边界的整个单词匹配。就我而言,我正在构建拼写检查器,因此只需要突出显示整个单词即可。 (2认同)