代码之家  ›  专栏  ›  技术社区  ›  faressoft

jquery中有文本选择器吗?

  •  1
  • faressoft  · 技术社区  · 14 年前

    jquery中有文本选择器吗?

    我的密码

    <anything>Hello World! Hello World!</anything>
    

    reslut应该是(使用jquery)

    <anything>Hello <span>World</span>! Hello <span>World</span>!</anything>
    
    3 回复  |  直到 14 年前
        1
  •  1
  •   Å ime Vidas Zim84    14 年前
    $('anything').html(function(i, v) {
        return v.replace(/(World)/g, '<span>$1</span>');
    });  
    

    上面的代码片段使用了jquery1.4中添加的功能。

    注: 此解决方案对于只包含原始文本(不包含子元素)的元素是安全的。

        2
  •  2
  •   bobince    14 年前

    不需要。jquery主要与元素一起工作,只提供很少的文本处理功能。

    要在文本上进行查找和替换,需要分别检查每个文本节点并执行DOM。 splitText 找到匹配项时将其分离的操作。例如:

    function findText(element, pattern, callback) {
        for (var childi= element.childNodes.length; childi-->0;) {
            var child= element.childNodes[childi];
            if (child.nodeType==1) {
                var tag= child.tagName.toLowerCase();
                if (tag!=='script' && tag!=='style' && tag!=='textarea')
                    findText(child, pattern, callback);
            } else if (child.nodeType==3) {
                var matches= [];
                var match;
                while (match= pattern.exec(child.data))
                    matches.push(match);
                for (var i= matches.length; i-->0;)
                    callback.call(window, child, matches[i]);
            }
        }
    }
    
    findText(element, /\bWorld\b/g, function(node, match) {
        var span= document.createElement('span');
        node.splitText(match.index+match[0].length);
        span.appendChild(node.splitText(match.index));
        node.parentNode.insertBefore(span, node.nextSibling);
    });
    
        3
  •  1
  •   Nick Craver    14 年前

    对于简单的情况,您可以执行regex替换等操作,但对于更一般的答案: .

    jquery在处理文本节点时没有提供太多帮助,它主要是为处理元素节点类型而设计的。( nodeType == 1 )不是文本节点类型( nodeType == 3 )…所以是的,你可以用它 在哪里? 它有帮助(例如) .contents() .filter() 但这不会经常发生,因为这不是图书馆的主要目的。