使用jQuery查找并包装文本字符的每个实例 [英] find and wrap every instance of a text character in a span using jQuery

查看:87
本文介绍了使用jQuery查找并包装文本字符的每个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想在页面上找到字符的每个实例(特别是),然后将其包裹在一个跨度中,以便为它们设置样式.它们可能位于DOM的各种元素中,并且遍及整个DOM:<nav/><h1/><p/>等.

We want to find every instance of a character (specifically, ) on a page, then wrap it in a span so we can style them. They could be within all sorts of elements, multiple times, and all over the DOM: <nav/>, <h1/>, <p/>, etc.

我们尝试了一种在此处找到的方法,该方法与匹配字符串并在其周围环绕一个跨度有关,但它似乎仅匹配并包装任何给定元素中的第一个实例,而忽略同一元素中的任何后续实例.例如,对于<p>•</p> <p>•</p>,两者都被匹配并包装,但是<p>blah • blah • blah • blah</p>,只有第一个被匹配并包装.

We've tried one method found here related to matching a string and wrapping a span around it, but it seems to only match and wrap the first instance within any given element and ignore any subsequent instances within the same element. For example, for <p>•</p> <p>•</p>, both get matched and wrapped, but <p>blah • blah • blah • blah</p>, only the first gets matched and wrapped.

这是我们尝试过的:

$('*:contains("•")').each(function() {
   if($(this).children().length < 1)
      $(this).html($(this).text().replace('•','<span class="bullets">•</span>'))
});

不确定是否与if行有关...这是我们唯一不了解的部分.但是,这种方法并没有特别投入,因此,如果有更清洁的东西,让我们听听吧!

Not sure if it has something to do with the if line... that's the only part that we're fuzzy about. Not particularly invested in this approach, however, so if there is something cleaner, let's hear it!

推荐答案

这是怎么回事:-

$('body:contains("•")').contents().each(function () {
    if (this.nodeType == 3) {
        $(this).parent().html(function (_, oldValue) {
            return oldValue.replace(/•/g, "<span class='bullets'>$&</span>")
        })
    }
});

尝试避免使用*.甚至body.尝试使用最外面的容器.

Try avoid using *. probably even body. Try using the outermost container as possible.

这也应该起作用

$('body:contains("•")').contents().each(function () {
    if (this.nodeType == 1) { //Look for only element Nodes
        $(this).html(function (_, oldValue) {
            return oldValue.replace(/•/g, "<span class='bullets'>$&</span>")
        })
    }

节点类型

这篇关于使用jQuery查找并包装文本字符的每个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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