开发者

Javascript functions return lines of function code or "{[native code]}," what am I doing wrong?

I am writing some code to find the user selection in a contenteditable div, I'm taking my code from this quirksmode article.

function findSelection(){
  var userSelection;
  if (window.getSelection) {userSelection = window.getSelection;} 
   else if (document.selection){userSelection = document.selection.createRange();} // For microsoft
  if (userSelection.text){return use开发者_StackOverflow社区rSelection.text} //for Microsoft
   else {return userSelection} 
  } 

I'm testing it in Chrome and Firefox, if I do an alert(userSelection) within the function or an alert(findSelection();) outside the function, it returns function getSelection() {[native code]}. If I do console.log(findSelection();) it gives me getSelection(). Is there something I've done wrong?


getSelection is a function... you need to execute it to get the selection?

if (window.getSelection) {userSelection = window.getSelection();}


Change it to

  if (window.getSelection) {userSelection = window.getSelection();}

(getSelection())


This is to get the text of the selection. Even with the typo fixed, you've got inconsistent behaviour: IE is returning the selection's text as a string while other browsers will return a Selection object that will give you the selection text string only when its toString() method is called.

The following would be better:

function getSelectionText(){
    if (window.getSelection) {
        return "" + window.getSelection();
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange().text;
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜