不能读取属性'copycode.js中的null

Cannot read property 'addEventListener' of null in copycode.js

本文关键字:copycode js 中的 null 不能读 读取 属性 不能      更新时间:2023-09-26

当我点击检查元素,我得到错误复制剪贴板工具提示:

无法读取属性'addEventListener'为null.

下面是我的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)

错误

无法读取null属性'XXX' .

表示您正在处理包含null的变量。如果您实际尝试调试您的程序并使用console.log,您将看到变量buddhaquote包含null而不是您想要的元素。

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

  1. id为mytext的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>
    

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

尝试将您的代码纳入

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

检查您是否没有尝试获取而不是id