In the popup window, selText does have the value "great," but the length is always undefined
. Something related with the encoding of the string?
var selText = document.getSelection(); //suppose "great" is selected
alert( "selected ->" + selText + " len is " + selText.length);
In the popup window, selText does have the value "great," but the length is always undefined
. Something related with the encoding of the string?
var selText = document.getSelection(); //suppose "great" is selected
alert( "selected ->" + selText + " len is " + selText.length);
Share
Improve this question
edited Mar 21 at 22:00
TylerH
21.1k78 gold badges79 silver badges114 bronze badges
asked Feb 12, 2011 at 16:44
pierrotlefoupierrotlefou
40.8k39 gold badges139 silver badges175 bronze badges
3 Answers
Reset to default 32Because you're getting a DOM selection object instead of a String. To get the text, call toString()
.
var selText = document.getSelection().toString();
The reason the string successfully shows up in the alert, is that the concatenation causes an implicit toString()
to occur.
The MDN documentation states.
In the above example, selObj is automatically "converted" when passed to window.alert. However, to use a JavaScript String property or method such as length or substr, you must manually call the toString method.
-- https://developer.mozilla/en/window.getSelection
It's suggesting you call document.getSelection().ToString().length;
Deprecated method document.getSelection() Try use window.getSelection().
var selText = window.getSelection().toString();
if(selText)
{
alert( "selected ->" + selText + " len is " + (selText.length - 1));
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743494496a4463129.html
评论列表(0条)