替换文本但不替换HTML标记? [英] Replace text but not the HTML tags?

查看:79
本文介绍了替换文本但不替换HTML标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对JQuery中的自动完成进行文本匹配,方法是重载_renderItem方法以检查用户搜索的文本的JSON对象。找到它之后,我用一个带有user_highlight_match类的span标签替换它。

I'm doing text matching on an Autocomplete in JQuery, by overloading the _renderItem method to check the JSON object for the text the user searched for. Upon finding it, I'm replacing it with a span tag with a "user_highlight_match" class.

我正在进行多字搜索,所以John Smi会突出显示John,然后是Smi,搜索John James Smi会突出John和Smi。这个问题是,比如你搜索John Las,它会开始匹配span标签的class属性,如果它已经存在的话。我怎么能绕过这个?

I'm doing multi word searching, so "John Smi" would highlight John, then Smi, and searching "John James Smi" would highlight "John" and "Smi". The problem with this is that, say you search for "John Las", it will start matching against the class attribute of the span tag, if it's already there. How can I get around this?

编辑:这里有一些代码显示我在说什么:

Here's some code showing what I'm talking about:

renderItem = function(ul, item) {
    li = $('<li>', id: item._id);

    if this.term and not item.dialog
        terms = this.term.split(' ');

        for term in terms
            re = new RegExp("("+term+")", 'i');

            match = re.exec(item.name);
            if match
                item.name = item.name.replace re, "<span class=\"user_highlight_match\">+match[0]+</span>";
)

所以第一个学期将匹配罚款,但每次在此之后,如果你在html标签中搜索任何东西,部分匹配被替换为标签。所以说las上有一场比赛,它会变成这样:

So the first term will match fine, but every time around after that, if you're searching for anything in the html tags, the partial match is replaced with a tag. So say there was a match on "las", it would become this:

<span c<span class="user_highlight_match">Last</span>s="user_highlight_match">Last</span>


推荐答案

您必须搜索文本节点并替换它们用你想要的HTML。请参阅此问题:在HTML中查找字词

You'll have to search text nodes and replace them with the html you want. See this question: Find word in HTML.

编辑:这是我的答案的jQuery版本。

Here's a jQuery version of my answer there.

http://jsfiddle.net/gilly3/auJkG/

function searchHTML(searchString, htmlString) {
    var expr = new RegExp(searchString, "gi");
    var container = $("<div>").html(htmlString);
    var elements = container.find("*").andSelf();
    var textNodes = elements.contents().not(elements);
    textNodes.each(function() {
        var matches = this.nodeValue.match(expr);
        if (matches) {
            var parts = this.nodeValue.split(expr);
            for (var n = 0; n < parts.length; n++) {
                if (n) {
                    $("<span>").text(matches[n - 1]).insertBefore(this);
                }
                if (parts[n]) {
                    $(document.createTextNode(parts[n])).insertBefore(this);
                }
            }
            $(this).remove();
        }
    });
    return container.html();
}

这篇关于替换文本但不替换HTML标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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