【问题标题】:Javascript functions return lines of function code or "{[native code]}," what am I doing wrong?Javascript 函数返回函数代码行或“{[native code]}”,我做错了什么?
【发布时间】:2010-05-12 16:11:01
【问题描述】:

我正在编写一些代码来在内容可编辑的 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()。是不是我做错了什么?

【问题讨论】:

    标签: javascript contenteditable getselection


    【解决方案1】:

    getSelection 是一个函数……你需要执行它来获取选择吗?

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

    【讨论】:

      【解决方案2】:

      改成

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

      (getSelection())

      【讨论】:

        【解决方案3】:

        这是获取选择的文本。即使错字已修复,您的行为也会不一致:IE 将选择的文本作为字符串返回,而其他浏览器将返回一个 Selection 对象,该对象仅在调用其 toString() 方法时才会为您提供选择文本字符串。

        以下会更好:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-16
          相关资源
          最近更新 更多