jQuery 查找文本并添加类

标签 jquery css replace

我的 HTML 结构:

<div id="test-listing">
<article>
<a>Some URL</a><h3>Some Text</h3>
<p>Drink this coffee</p>
</article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffee</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this Coffeeland</p></article>
<article><a>Some URL</a><h3>Some Text</h3><p>Drink this coffees</p></article>
</div>

我的 CSS 类:

.hit-list {
    background: none repeat scroll 0 0 rgba(255, 0, 0, 0.1);
    border-bottom: 1px solid #FF0000;
}

我需要搜索文本 coffee,而不考虑区分大小写。请注意,咖啡文字可能类似于 coffeecoffeesCoffeeCoffeeland 并将其应用于特定类别。所以生成的代码将是

<div id="test-listing">
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">coffee</span></p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">Coffee</span></p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">Coffee</span>land</p>
      </article>
      <article><a>Some URL</a><h3>Some Text</h3
       <p>Drink this <span class="hit-list">coffee</span>s</p>
      </article>  
    </div>

我搜索了相关帖子,但没有找到任何东西,因为我正在处理循环内的内容。我也不需要 jQuery 插件来实现这一点。

谢谢。

最佳答案

你可以这样做:

$('div#test-listing article').html(function () {
    return $(this).html().replace(/coffee(?=[^>]*<)/ig, "<span class='hit-list'>$&</span>");
});

如果搜索词是动态的,您可以这样做:

var term = 'coffee';
$('div#test-listing article').html(function () { 
    return $(this).html().replace(new RegExp(term + "(?=[^>]*<)","ig"), "<span class='hit-list'>$&</span>");
});

Updated Demo

关于jQuery 查找文本并添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23441264/

相关文章:

php - 如何用我自己的文本替换某些 PHP 值?

Javascript 替换功能在第一个实例上不起作用

php - 通过jquery和ajax发布两个变量

javascript - 如何在我的代码中使用 jquery 验证和 jquery 自动完成

javascript - 使用 jQuery 将类添加到窗口垂直滚动中的不同 Div

jQuery 选择器没有按预期工作(多个 :not selector not working?)

css - Angular Material CSS 控制台警告

javascript - Bootstrap 工具提示延迟加载并显示

html - ionic 定制子标题涵盖 ion-content

python - 如何将列中的整数替换为另一个文件、python 或 awk 中包含的另一个整数