2011-02-12 164 views
14

在弹出窗口中,selText的值为“很好”,但长度始终为undefined。与字符串编码有关的东西?为什么string.length返回undefined?

var selText = document.getSelection(); //suppose "great" is selected 
alert("selected ->" + selText + " len is " + selText.length); 

回答

24

因为你得到的是DOM选择对象而不是String。要获得文本,请致电toString()

var selText = document.getSelection().toString(); 

原因字符串中的警报成功显示了,是串联导致隐含toString()发生。

2

MDN documentation状态。

在上述例子中,是selObj自动 “转换” 传递 时window.alert。但是,若要使用 JavaScript字符串属性或方法 (如length或substr),则必须手动调用toString方法 。
- https://developer.mozilla.org/en/window.getSelection

它提示你打电话document.getSelection().ToString().length;

+0

的MDN文档指的功能是`window.getSelection()`,`未document.getSelection()`,这是不普遍支持和现在换成由`window.getSelection所有当前的浏览器( )`。另外,它是`toString()`而不是`ToString()`。 – 2011-02-13 01:44:45

0

的方法已过时document.getSelection()尝试使用window.getSelection()。

var selText = window.getSelection().toString(); 
     if(selText) 
     { 
      alert("selected ->" + selText + " len is " + (selText.length - 1)); 
     }