TypeError: null不是对象(计算'document.getElementById(x).style&

TypeError: null is not an object (evaluating 'document.getElementById(x).style')

本文关键字:document getElementById style 计算 null 对象 TypeError      更新时间:2023-09-26

我想让我的javascript做什么:

我有一个div,其中包含一个"onmouseover='getPosition(x)'"是添加的,也可以在我的javascript中删除,当我按下某个按钮。函数'getPosition()总是在div尚未删除时运行,以便它总是获取和更新div的位置,并在文本字段占位符

中显示它的x和y位置。
$("#canvas").append('<div onmouseover="getPosition(this.id);"style="top:'+initXYpos+'px; left:'+initXYpos+'px;">Button '+index+'</div>');

问题:

当我删除包含"getPosition(this.id)"的div时,它仍然运行该函数,同时给出一个错误:"TypeError: null不是对象(求值'document.getElementById(x).style')"

我只是想让它停止运行当我删除div。

getPosition(x):

function getPosition(x){   
    $('#canvas_container').mouseover(function(){
    timer =  setInterval(function() {
      var xPos = document.getElementById(x).style.left;
      var yPos = document.getElementById(x).style.top;
      document.getElementById(x+'_fieldX').placeholder = xPos;
      document.getElementById(x+'_fieldY').placeholder = yPos;
    }, 10); }

注意:

如果你认为我的问题是由一个愚蠢的错误引起的,我很抱歉。我对Javascript真的很陌生,希望你能理解并乐于帮助我。

在您的javascript中,当您删除div时,您还必须使用以下代码行停止计时器:

clearInterval(timer);  

我的建议是删除计时器,因为你并不真的需要它来实现你想要做的事情