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

社会主义新天地 提交于 2019-12-13 04:43:57

问题


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 userSelection.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?


回答1:


Change it to

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

(getSelection())




回答2:


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

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



回答3:


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


来源:https://stackoverflow.com/questions/2820650/javascript-functions-return-lines-of-function-code-or-native-code-what-am

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!