What is the difference between function declaration and anonymous function? (Front-end novice asking for help...)
高洛峰
高洛峰 2017-07-05 10:59:56
0
3
913

Defining a function that changes the style attribute of an element using a function declaration will report an error

#But no error will be reported under window.onload

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
大家讲道理

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?

function change () { /* ... */ }
window.onload = change

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(){......}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!