jQuery查找/替换而不更改原始文本 [英] jQuery find/replace without changing original text

查看:105
本文介绍了jQuery查找/替换而不更改原始文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery中是否有一种方法可以在jQuery中查找文本字符串,而不是用其他内容替换它,但是将该文本用元素包装起来,这样当脚本完成后,它会将原始文本用文本字符串包装出来。

Is there a way in jQuery to find a string of text in jQuery and not replace it with something else but wrap that text with an element so when the script is finished it spits out the original text with the string of text wrapped.

示例:

原始文本

"Hello world to all people"

搜索字符串

"world to"

替换为< i>< / i>

最终输出

"Hello <i>World to</i> all people"

预先感谢您的帮助!

工作代码种类:

function highlightChild(child) {
        $(childElements[child]).text("");
        console.log(child);
        $('.child_element_' + child).bind('textselect', function(e){
            var selection = e.text;
            var str = $("#construct_version").text();
            var wrap = jQuery(childElements[child]).text(selection);
            var re = new RegExp("" + selection + "", "g");

            console.log(str.replace(selection, function(match, key, val){
                console.log(match);
                console.log(key);
                console.log(val);
                jQuery(childElements[child]).text(val)
            }));
        });
    }

以上代码执行替换,但实际执行的替换显示为未定义。

The above code does the replace but where it actually does the replace it shows as undefined.

因此,如果原始字符串是所有人的Hello world,并且我想将< b>世界替换为< / b> ,它在console.log中显示为Hello undefined all

So if the original string is Hello world to all and I am wanting to replace world to with <b>world to</b>, it shows in the console.log as Hello undefined all

推荐答案

更改页面内容是通常,不像用正则表达式替换 html()标记一样简单。如果标记本身存在匹配的文本,那么所有这些尝试都将失败,当浏览器选择以不符合您期望的方式序列化其DOM时可能会失败,并且最好,当它确实有效时,仍会强制您序列化并重新解析所有搜索到的文本,这些文本很慢并且会破坏所有不可序列化的信息,例如表单字段值,JavaScript引用和事件处理程序。对于简单的低级元素,您可以使用它,但对于像< body> 这样的容器,它会很糟糕。

Altering page content is not, in general, as simple as replacing the html() markup with regex. All such attempts will fail where there is matched text in the markup itself, can fail when the browser chooses to serialise its DOM in a way that doesn't meet your expectations, and at best, when it does work, still forces you to serialise and re-parse all searched text, which is slow and destroys all non-serialisable information, such as form field values, JavaScript references and event handlers. You can get away with that for simple low-level elements, but against a container like <body> it'd be awful.

更好:不是黑客攻击HTML字符串,而是坚持使用实时DOM节点,搜索符合您要求的文本节点并对其进行替换。直文节点数据。这里有一些简单的JS代码(如果你愿意的话,我想你可以将它放在一个插件中。)

Better: instead of hacking at an HTML string, stick with the live DOM nodes, searching for Text nodes that match your requirements and doing the replacements on the straight text node data. Here's some plain JS code to do that (I guess you could put it in a plugin if you wanted.)

// Utility function to find matches in an element's descendant Text nodes,
// calling back a function with (node, match) arguments. The `pattern` can
// be a string, for direct string matching, or a RegExp object (which must
// be a `g`lobal regex.
//
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= [];
            if (typeof pattern==='string') {
                var ix= 0;
                while (true) {
                    ix= child.data.indexOf(pattern, ix);
                    if (ix===-1)
                        break;
                    matches.push({index: ix, '0': pattern});
                }
            } else {
                var match;
                while (match= pattern.exec(child.data))
                    matches.push(match);
            }
            for (var i= matches.length; i-->0;)
                callback.call(window, child, matches[i]);
        }
    }
}

普通字符串的示例用法搜索字词:

Example usage with a plain string search term:

// Replace "World to" string in element text with <i>-wrapped version
//
var element= $('#construct_version')[0];
findText(element, 'World to', function(node, match) {
    var wrap= document.createElement('i');
    node.splitText(match.index+match[0].length);
    wrap.appendChild(node.splitText(match.index));
    node.parentNode.insertBefore(span, node.nextSibling);
});

这篇关于jQuery查找/替换而不更改原始文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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