search

Home  >  Q&A  >  body text

What is the difference between function declaration and anonymous function? (Front-end novice asking for help...)

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

高洛峰高洛峰2758 days ago974

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-07-05 11:01:56

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-07-05 11:01:56

    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.

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-07-05 11:01:56

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

    reply
    0
  • Cancelreply