问题
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>
回答1:
Remove the # from the identifier:
var hint = "Hello";
function ahint()
{
document.getElementById('randomhint').innerHTML = hint;
}
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.
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.
来源:https://stackoverflow.com/questions/54554975/why-am-i-getting-cannot-set-property-innerhtml-of-null-at-ahint