2010-08-06 78 views

回答

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> 
+0

謝謝ironsam,它的工作原理=) – 2010-08-06 08:47:23