Why can't this simple javascript / jquery code display the selected text?

I can not explain the behavior of the code below. Here is all my script

<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
<script type="text/javascript" language="javascript">
var tmpText = '';
$(document).ready(function(){
        tmpText = '';
        $('#btn_bold').click(function(){alert(tmpText);});
        $('textarea').bind('mouseup', function(){
                  tmpText = '';
                  if(window.getSelection){
                    tmpText = window.getSelection();
                  }else if(document.getSelection){
                    tmpText = document.getSelection();
                  }else if(document.selection){
                    tmpText = document.selection.createRange().text;
                  }
                //tmpText = 'hello world';
                alert(tmpText);
        });
});

</script>
</head>
<body>
<button type="button" id="btn_bold">click</button>
<textarea>This is some text</textarea>
</body>
</html>

Try the following operations:

1) Use the mouse for text with high light in the text area. You will notice that javascript warns you of the selected text.

2) Click the click button. You will notice that javascript will warn you about an empty line.

Do not uncomment tmpText = 'hello world';and repeat the steps above. This time you will notice that both steps 1) and 2) notify you “hello world”.

As in the first experiment, step 2) does not tell you the same text as step 1)?

I am testing on google chrome

0
source share
3 answers

. alert(), toString , , , , , , -, ( ).

toString() , .

if(window.getSelection){
                    tmpText = window.getSelection().toString();
                  }else if(document.getSelection){
                    tmpText = document.getSelection().toString();
                  }else if(document.selection){
                    tmpText = document.selection.createRange().text;
                  }

jsfiddle

, mozilla getSelection, , .

EDIT: mozilla, , , "".

+4

( ) - . , , :

jsFiddle: http://jsfiddle.net/fxN7p/

:

function getTextareaSelectedText(textarea) {
    var text = "";
    if (typeof textarea.selectionStart == "number") {
        text = textarea.value.slice(textarea.selectionStart, textarea.selectionEnd);
    } else if (typeof document.selection != "none" && document.selection.type == "Text") {
        text = document.selection.createRange().text;
    }
    return text;
}
0

Hii ...

you need to convert to a selection string ... example

window.getSelection().toString()

otherwise you will not be able to access the data

0
source

All Articles