Javascript 多次出现文本的getSelection将替换第一次出现的文本而不是正确的选择
我很难选择文本并在多次出现时替换该选择。它总是恢复到第一次出现并替换它 这是我正在使用的脚本,如果选择只在我完成后出现。当它多次出现时,它会抓住第一个Javascript 多次出现文本的getSelection将替换第一次出现的文本而不是正确的选择,javascript,jquery,getselection,Javascript,Jquery,Getselection,我很难选择文本并在多次出现时替换该选择。它总是恢复到第一次出现并替换它 这是我正在使用的脚本,如果选择只在我完成后出现。当它多次出现时,它会抓住第一个 var self=$('#textarea'); GetSelected={}; GetSelected=function(){ var txt=''; if(window.getSelection){ txt=window.getSelection(); } else if(document.ge
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>'));
var self=$('#textarea');
GetSelected={};
GetSelected=函数(){
var-txt='';
if(window.getSelection){
txt=window.getSelection();
}
else if(document.getSelection){
txt=document.getSelection();
}
else if(文档选择){
txt=document.selection.createRange().text;
}
返回txt;
}
html(self.html().replace(selection,“+selection+”);
是否有我缺少的东西,知道要替换哪个选项?要替换所有出现的内容,您需要使用
/g
。请尝试self.html(self.html().replace('/'+selection+'/g',''+selection+'');
这里的主要问题是,将HTML视为字符串并替换部分内容是一种非常脆弱的方法(例如,考虑一段匹配的文本,其中部分内容已为粗体,或者一个包含与选定文本匹配的属性值)。相反,你可以使用。以下是根据您的案例改编的该问题的功能:
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;
}
请注意,如果使用我建议的方法,则根本不需要此函数。您需要对选择本身进行操作,而不是尝试查找文本。这将因浏览器而异:
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();
}