jQuery选择文本并在段落中添加跨度 [英] jQuery select text and add span to it in an paragraph
本文介绍了jQuery选择文本并在段落中添加跨度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个获取所选文本的功能,该文本是通过鼠标选择的,并将其添加到变量中.我想在所选文本中的该变量周围添加标签-在该段落中.
I have a function that gets the selected text, the text is selected by mouse, and add it into a variable. I want to add tags around that variable in the selected text - in that paragraph.
$("p").live("mouseup",function() {
selection = getSelectedText();
if(selection.length >= 3) {
var $spn = $("<span></span>").html(selection).addClass("selected");
$("p").wrap($spn);
}
});
//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;
}
}
我可以获取文本选择变量,但是我的函数不是将<span></span>
放在段落<p>
的所选文本周围,而是将其包装在外部.
I can get the text selection variable but instead of placing the <span></span>
around the selected text from the paragraph <p>
, my function wraps this outside.
如何在段落中替换它? 谢谢.
How can I replace it in the paragraph? Thank you.
推荐答案
这是出问题的地方:
var $spn = $("<span></span>").html(selection).addClass("selected");
$("p").wrap($spn);
这意味着您将span
包裹在段落中.
This means you’re wrapping the span
around the paragraph.
我认为您的意思是做这样的事情:
I think you mean to do something like this:
var spn = '<span class="selected">' + selection + '</span>';
$(this).html($(this).html().replace(selection, spn));
这篇关于jQuery选择文本并在段落中添加跨度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文