在元素中查找一串文本并在其周围包裹一些 span 标签 [英] Find a string of text in an element and wrap some span tags round it

查看:22
本文介绍了在元素中查找一串文本并在其周围包裹一些 span 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个元素中找到一串文本,并在它周围包裹一些 span 标签.例如

I want to find a string of text in an element and wrap some span tags round it. E.g.

来自:

<h2>We have cows on our farm</h2>

致:

<h2>We have <span class='smallcaps'>cows</span> on our farm</h2>

我试过了:

$("h2:contains('cow')").each(function() {
 $(this).text().wrap("<span class='smallcaps'></span>");
});

但这只包装了整个包含 h2 标签.

But that only wraps the whole containing h2 tag.

推荐答案

$("h2:contains('cow')").html(function(_, html) {
   return html.replace(/(cow)/g, '<span class="smallcaps">$1</span>');
});

http://jsfiddle.net/w5ze6/1/

这篇关于在元素中查找一串文本并在其周围包裹一些 span 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆