Baby, this has nothing to do with what function you use! It’s because onload will be triggered after the document is loaded, and you must be reporting an error because the document has not been loaded and the element is not found. Put the js under the element
This has nothing to do with function declaration and anonymity, but with the timing of function calling. If we change it to this, can we still find the problem with anonymous functions?
When the former is called, the box element is not yet available, so an error is reported; the latter is called after the DOM is ready, so it can be executed. You can log the box object in the change function and see.
The problem is not this. You need to know that the document is loaded from top to bottom. You put the js file in the head When the js file is executed, even the body has not been loaded at this time, so naturally the box cannot be obtained. , and the css cannot be set. You can put the js file at the end of body:
.
.
.
<script src="./x.js"></script>
</body>
This way there is no need for window.onload If it is placed in the head , you need to write window.onload=function(){......}
Baby, this has nothing to do with what function you use! It’s because onload will be triggered after the document is loaded, and you must be reporting an error because the document has not been loaded and the element is not found. Put the js under the element
This has nothing to do with function declaration and anonymity, but with the timing of function calling.
If we change it to this, can we still find the problem with anonymous functions?
When the former is called, the box element is not yet available, so an error is reported; the latter is called after the DOM is ready, so it can be executed. You can log the box object in the change function and see.
The problem is not this. You need to know that the document is loaded from top to bottom. You put the js file in the
head
When the js file is executed, even the body has not been loaded at this time, so naturally the box cannot be obtained. , and the css cannot be set.
You can put the js file at the end of
body
:This way there is no need for
window.onload
If it is placed in the head
, you need to write
window.onload=function(){......}