Replace text but not the HTML tags?

前端 未结 1 1138
清歌不尽
清歌不尽 2020-12-21 11:43

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\

相关标签:
1条回答
  • 2020-12-21 12:10

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

    Edit: 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();
    }
    
    0 讨论(0)
提交回复
热议问题