2016-08-22 113 views
-1

空的“的addEventListener”当我点击检查元素,我得到了拷贝剪贴板工具提示错误:无法读取财产copycode.js

无法读取空的特性“的addEventListener”。

下面是我的JS代码:

createtooltip() 
var buddhaquote = document.getElementById('mytext') 
buddhaquote.addEventListener('mouseup', function(e){ 
    var selected = getSelectionText() // call getSelectionText() to see what was selected 
    if (selected.length > 0){ // if selected text length is greater than 0 
     var copysuccess = copySelectionText() // copy user selected text to clipboard 
     showtooltip(e) 
    } 
}, false) 
+0

如何在'console.log'中打印'budhaquote'变量?或者,也许只是在控制台中运行'document.getElementById('mytext')'? –

回答

0

错误

无法读取空的特性 'XXX'。

表示您正在使用包含null的变量。如果你真的试图调试你的程序并使用console.log,你会看到这个变量buddhaquote包含null而不是你想要的元素。

这可能有两个原因,很难说,因为您决定不共享足够的代码。 ID为mytext

  1. HTML元素不存在
  2. 你试图创建真实之前它来访问元素。例如,这是错误的:

    <script> 
        var test = document.getElementById("test"); 
        // Error: Cannot read property 'appendChild' of null. 
        test.appendChild(new Text("Hello world!")); 
    </script> 
    <!-- only after this you can access span#test --> 
    <span id="test"></span> 
    

这是正确的:在

window.onload=function(){ --your code -- } 

<span id="test"></span> 
    <script> 
     var test = document.getElementById("test"); 
     test.appendChild(new Text("Hello world!")); 
    </script> 
0

尝试进化得只剩您的代码和检查,如果你是不是想获得而不是ID