Javascript函数返回函数代码行或“{[native code]},”我做错了什么?

时间:2010-05-12 16:11:01

标签: javascript contenteditable getselection

我正在编写一些代码来查找contenteditable div中的用户选择,我正在从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} 
  } 

我在Chrome和Firefox中测试它,如果我在函数中执行alert(userSelection)或在函数外部执行alert(findSelection();),则返回function getSelection() {[native code]}。如果我console.log(findSelection();)它会给我getSelection()。我做错了吗?

3 个答案:

答案 0 :(得分:2)

getSelection是一个函数......你需要执行它才能得到选择吗?

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

答案 1 :(得分:1)

将其更改为

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

getSelection ()

答案 2 :(得分:0)

这是为了获取选择的文本。即使修复了拼写错误,你也会有不一致的行为:IE将选择的文本作为字符串返回,而其他浏览器将返回Selection对象,只有在toString()时才会为您提供选择文本字符串方法被称为。

以下情况会更好:

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