2016-08-22 116 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