试图用包裹在跨度元素中的相同单词替换一个单词



我有一个 contenteditable div。我正在尝试寻找"设计"一词,并将其包裹在span元素中。

html

<div id="text"></div>

javascript:

$("#text").prop("contenteditable", true);
var string = $("#text")[0].innerHTML;
$("#text").innerHTML = string.replace("design", "<span>design</span>");

这不起作用。我的第一个猜测是因为脚本运行一次,所以当我键入"设计"时,它不会捕获它。因此,我尝试将其放入setInterval中,但这也没有用。 jsfiddle

任何帮助都将不胜感激。

$("#text").prop("contenteditable", true).keypress(function(e){
    $(this).html(function(i,html){return html.replace(/<span>design</span>/g,"design").replace(/design/g, "<span>design</span>")});
});

我没有测试,但希望它会起作用。

您可以像这样做

$('#text').prop("contenteditable", true).on('keyup change',function(){
    var $el = $(this);
    $el.find('span').contents().unwrap(); // remove existing spans around "design"
    $el.html(function(i,v){ 
       return v.replace(/bdesignb/gi, "<span>design</span>") // wrap design with spans
    });
    setEndOfContenteditable(this); // reset the cursor to the end
});

小提琴

setEndOfContenteditable功能是从此答案中获取的 - 它将光标设置为文本末尾https://stackoverflow.com/a/3866442/1385672

最新更新