2014-03-31 43 views
1

jquery .replace()不能处理长文本。 如果您突出显示一些单词的所有功能,但是如果选择所有文本都不起作用。jquery替换不能使用长文本

//Grab selected text 
function getSelectedText(){ 
    if(window.getSelection){ 
     return window.getSelection().toString(); 
    } 
    else if(document.getSelection){ 
     return document.getSelection(); 
    } 
    else if(document.selection){ 
     return document.selection.createRange().text; 
    } 
} 

$("p").on("mouseup",function() { 
    selection = getSelectedText(); 
}); 

$(".add-h1").on("click",function(e) { 
    e.preventDefault(); 
    alert(selection); 
    if(selection.length >= 1) { 
    var repl = '</p><h1>' + selection + '</h1><p>'; 
    $('body').html($('body').html().replace(selection, repl)); 
    selection = ""; 
    } 
}); 

Fiddle

回答

3

这并不是说是一个问题,但在你的选择返回的文本,并通过html返回的源文本之间的间距,而不一致的长度。例如,在您的原始HTML你有这样的:

fallback to users JavaScript disabled 

注意到有JavaScript前2位。但是,在由您的选择返回的文本中,这些空间被标准化为一个空格。

您可能会遇到类似的问题,与任何其他空白,行返回等,当然与任何嵌入的HTML标记。文本选择将返回看到的文本,而不是它在源标记中的文本。