2011-06-02 83 views
0

如果出現多次出現,我很難選擇文本並替換該選擇。它總是回覆到第一次出現並取而代之。getSelection出現多次文本替換第一次出現的不是正確的選擇

這是我正在使用的腳本,如果選擇只出現一次,我是完美的。當它不止一次出現時,它會抓住第一個。

var self=$('#textarea'); 
GetSelected={}; 
GetSelected=function(){ 
    var txt=''; 
    if(window.getSelection){ 
     txt=window.getSelection(); 
    } 
    else if(document.getSelection){ 
     txt=document.getSelection(); 
    } 
    else if(document.selection){ 
     txt=document.selection.createRange().text; 
    } 
    return txt; 
} 

self.html(self.html().replace(selection, '<b>' + selection + '</b>')); 

有什麼我不知道,知道哪個選擇要取代?

回答

0

要替換所有需要使用的事件,請使用/g。請嘗試self.html(self.html().replace('/' +selection+'/g', '<b>' + selection + '</b>'));

0

這裏的主要問題是,將HTML視爲字符串並將其部分替換爲您正在做的事情是一種非常脆弱的方法(想想一部分文本的匹配部分已經是粗體,例如,包含的文本屬性值與選定的文本匹配)。相反,你可以使用built-in browser behaviour to find matching text。下面是從這個問題適合你的情況的功能:

function doSearch(text) { 
    if (window.find && window.getSelection) { 
     document.designMode = "on"; 
     var sel = window.getSelection(); 
     sel.collapse(document.body, 0); 

     while (window.find(text)) { 
      document.execCommand("Bold", false, null); 
      sel.collapseToEnd(); 
     } 
     document.designMode = "off"; 
    } else if (document.body.createTextRange) { 
     var textRange = document.body.createTextRange(); 
     while (textRange.findText(text)) { 
      textRange.execCommand("Bold", false, null); 
      textRange.collapse(false); 
     } 
    } 
} 

此外,GetSelected功能是不正確的(雖然它巧合的是不工作在這種情況下),它返回IE < 9字符串和Selection對象在其他瀏覽器中。您還沒有聲明GetSelected變量。這裏有一個更簡單和更好的替換:

function GetSelected() { 
    var txt = "" 
    if (window.getSelection) { 
     txt = window.getSelection().toString(); 
    } else if (document.selection && document.selection.type == "Text") { 
     txt = document.selection.createRange().text; 
    } 
    return txt; 
} 

請注意,如果您使用我建議的方法,則根本不需要此功能。

0

而不是試圖找到文本,你需要採取行動的選擇本身。這取決於瀏覽器會有所不同:

var t = $("#textarea")[0]; 
if (t.setSelectionRange) 
{ 
    var selStart = t.selectionStart; 
    var selEnd = t.selectionEnd; 
    var val = t.value; 
    var startVal = val.substring(0, selStart); 
    var selectedVal = val.substring(selStart, selEnd); 
    var endVal = val.substring(selEnd); 
    var bold = selectedVal.bold(); 
    t.value = startVal + bold + endVal; 
} 
else if (document.selection && document.selection.createRange) 
{ 
    var selection = document.selection.createRange(); 
    selection.text = selection.text.bold(); 
} 
相關問題