本文介绍了为什么我会收到“无法在ahint设置null的属性'innerHTML'的信息"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用JS编写一些代码,但是,当我将鼠标悬停在鼠标上时,会看到错误无法在ahint处设置null的'innerHTML'属性".我已经读到可能会发生这样的错误,因为Chrome甚至在创建Div之前都会编译/渲染JS代码.因此,我将其放在底部进行检查.不幸的是,把它放在最底下并不能解决我的问题.也许更有经验的人会理解它.

I have tried to write some code in JS but, when I hover my mouse, the error "Cannot set property 'innerHTML' of null at ahint" is seen. I have read that such an error can occur because Chrome compiles/renders the JS code before the Div is even created. Therefore, I have put it on the bottom to check it. Unfortunately, putting it on the bottom has not solved my problem. Maybe someone more experienced will understand it.

var hint = "Hello";

function ahint()
{
    document.getElementById('#randomhint').innerHTML = hint;
}
    <div id="randomhint" onmouseover="ahint()">!</div>

    <script type="text/javascript" src="main.js"></script>
</body>

推荐答案

从标识符中删除#:

var hint = "Hello";

function ahint()
{
    document.getElementById('randomhint').innerHTML = hint;
}

您可能已经在使用jQuery或类似库的代码中看到了#,例如 $('#randomhint').这样,这些库就知道您是要使用 id 而不是使用标记名.

You have likely seen the # in code that uses jQuery or a similar library, as in $('#randomhint'). That’s how those libraries know that you mean to use an id and not, say, a tag name.

但是,当使用 getElementById (它是原始" JavaScript的一部分)时,您不需要(也不能使用)它.对于 getElementById ,只有实际的 id 值("randomhint" )才属于该字段.

But you do not need (and cannot use) it when using getElementById (which is part of "vanilla" JavaScript). With getElementById, only the actual id value ("randomhint") belongs there.

这篇关于为什么我会收到“无法在ahint设置null的属性'innerHTML'的信息"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 07:03