使用jQuery替换所选文本的第n个位置

问题描述

|| 我有以下div:
<div id=\"target\" >hello(first),hello(second),hello(third),hello(fourth)</div>
以及基于此讨论的以下代码
    $(document).ready(function(){
      $(\'#target\').bind(\'mouseup\',function(){
           var needle = window
            .getSelection()
            .getRangeAt(0);
           var haystack = $(this).text();
           var newText = haystack.replace(needle,\'<span class=\"highlight\">\' + needle + \'</span>\');
           $(this).html(newText);             
      });   
当我选择“ hello”之一时,它“随机”突出显示其中之一,而不是实际选择的“ hello”。 如何突出显示所选内容? 在此先感谢您的帮助。     

解决方法

        这似乎很有效:
$(\'#target\').bind(\'mouseup\',function(){
    var needle = window.getSelection().getRangeAt(0);
    var start = window.getSelection().anchorOffset;
    var end = window.getSelection().focusOffset;
    var haystack = $(this).text();
    var startHighlight = \'<span class=\"highlight\">\';
    var endHighlight = \'</span>\';
    var nodeContent = window.getSelection().anchorNode.textContent;

    // If the selection goes backward,switch indexes
    if (end < start)
    {
        var tmp = start;
        start = end;
        end = tmp;
    }

    // If there is a span
    if ($(\'span\',this).size() > 0)
    {
        // If the selection starts after the span,compute an offset for start and end
        if (haystack.substr(0,nodeContent.length) != nodeContent)
        {
            var diff = $(this).html().indexOf(startHighlight) + $(\'span\',this).text().length;
            start += diff;
            end += diff;
        }

        // Remove the span
        var spanText = $(\'span\',this).contents().filter(textNodeFilter);
        $(spanText).unwrap();
    }

    var newText = haystack.substring(start,end).replace(needle,startHighlight + needle + endHighlight);
    haystack = haystack.substring(0,start) + newText + haystack.substring(end);

    $(this).html(haystack);
});