我试图从某些图像的 onerror 事件中访问和更改某些元素的属性。但是...当我加载页面时,我得到 Uncaught TypeError: Cannot call method ... of null。我知道这通常是因为元素尚未加载。
我使用 setTimeout 添加了 10 秒的延迟。现在,我加载了代码,并通过控制台(在 Chrome 和 Firefox 中)成功地到达了元素。我仍然收到 TypeError 消息。
请注意,“onerror”中的代码在控制台上可以正常工作。
我试图以另一种方式做我想做的事:我试图从图像的“onerror”属性中重新定义一个全局函数。但同样:全局函数没有改变。这不是时间问题,代码在控制台中运行良好(相同的 onerror 代码,在 Chrome 和 FF 中都成功地从控制台重新定义了全局函数)。
我将在这里带来一些我所做的尝试示例(我很快重写了它们,希望没有任何错字):
<img src='' onerror='setTimeout(function(){document.getElementById(someElementString).addEventListener(clickString,function(){alert(1234);});},6000);' height=100 width=100 />
<img src='' onerror='function(){setTimeout(function(){document.getElementById(someElementString).addEventListener(clickString,function(){alert(1234);});},6000);};' height=100 width=100 />
<img src='' onerror='f = function(){setTimeout(function(){document.getElementById(someElementString).addEventListener(clickString,function(){alert(1234);});},6000);}; f();' height=100 width=100 />
<img src='' onerror='setTimeout(function(){window.globalFunction = function(e){alert(656565);};},6000);' height=
200 width=100 />
我还将 onerror 包装为一个函数,但没有成功。
如果我用一个简单的警报替换 onerror 代码,它就可以工作;再说一遍:它也可以从控制台工作,甚至在代码 onerror 代码运行之前。
这可能是什么原因?任何帮助将不胜感激!