使用jquery突出显示特定位置的文本

时间:2010-08-06 04:19:15

标签: javascript jquery

我想突出显示特定位置的文字。这样的事情:highlight with jquery,但它只突出显示位置 n 中的单词。

例如,在文本“hello,hello,hello”中仅突出显示 second hello

谢谢

1 个答案:

答案 0 :(得分:3)

这是一种方法,但它不是一些简洁明快的jQuery - 大多是直接的javascript。

<div id="content">hello, hello, hello</div>

<script type="text/javascript">
    $(document).ready(function() {
        var searchKey = "hello"; // text to search for in element
        var elementToSearch = $("#content");  // jquery element with text to search for matches
        var instanceToHighlight = 2; // 1-based;  e.g. 3 = third instance found
        highlightText(searchKey, elementToSearch, instanceToHighlight);
    });

    function highlightText(searchKey, elementToSearch, instanceToHighlight) {
        var content = elementToSearch.html();
        var highlightIndex = instanceToHighlight - 1;
        var lastIndex = -1;
        var i = 0;
        // get the index in the overall text of the instance to highlight
        while (i <= highlightIndex) {
            lastIndex = content.indexOf(searchKey, lastIndex + 1);
            i++;
        }
        var testValue = content.slice(lastIndex, lastIndex + searchKey.length);
        if (testValue !== searchKey) {
            return;  // didn't find an actual match
        }
        // chop up the content string so that the <span> tag can be wedged in around the text to highlight
        var contentBeforeHighlightText = content.substr(0, lastIndex);
        var contentAfterHighlightText = content.substr(lastIndex + searchKey.length, content.length - 1);
        highlightedText = "<span class=\"highlight\">" + searchKey + "</span>";
        content = contentBeforeHighlightText + highlightedText + contentAfterHighlightText;
        elementToSearch.html(content);
    }
</script>