开发者

jQuery select text and add span to it in an paragraph

开发者 https://www.devze.com 2022-12-19 14:41 出处:网络
I have a function that gets the selected text, the text is selected by mouse, and add it into a variable. I want to addtags around that variable in the selected text - in that paragraph.

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;
    }
}

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.


This is where it goes wrong:

var $spn = $("<span></span>").html(selection).addClass("selected");
$("p").wrap($spn);

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));


Use .wrapInner() instead of .wrap()


Try to trim the selection and replace html-internal line breaks. This helps a lot:

$('#tweet_contents').live("mouseup",function() {
    selection = getSelectedText().replace(/^\s+|\s+$/g,"");

    if(selection.length >= 4) {
        var spn = '<span id=\"selected\" class=\"polarite\"  selcount=\"'+selcounter+'\" >'+selection+'<span id=\"superscript\">'+selcounter+'<\/span>'+'<\/span>';

    $(this).html( $(this).html().replace(/(\r\n|\n|\r)/gm," ").replace(selection, spn ) ); 
    }
});


Untested, but should work:

$("p").live("mouseup",function() {
selection = getSelectedText();
if(selection.length >= 3) {
var $spn = $("<span></span>").html(selection).addClass("selected");
$(this).html($(this).html().replace(selection, $spn);
}
});


I think you'll need to replace the text in the paragraph, not use wrap.

$("p").live("mouseup",function() {
   selection = getSelectedText();
   if(selection.length >= 3) {
      var spn = "<span class='selected'>" + selection + "</span>");
      var html = $(this).html().replace(selection,spn);
      $(this).html(html);
    }
});

Note that this is only going to work reliably if the paragraph contains only text and no markup.

0

精彩评论

暂无评论...
验证码 换一张
取 消