when has a function to be in $(document).ready()

前端 未结 2 749
悲哀的现实
悲哀的现实 2021-02-15 02:06

I just don\'t get it. I searched and searched but for this I just can\'t figure out what\'s \"right\".

There are three examples.

1) Fiddle 1.0 Here we have

2条回答
  •  感情败类
    2021-02-15 02:10

    In JavaScript, scope is handled on a per-function basis. Anything in scope of a function can access other things in scope of that function and things in a wider scope.

    Defining a variable with var inside a function will limit the scope of that variable to the function.

    Defining a function with a function declaration inside another function will limit the scope of the defined function to the container function.

    When you use ready, you pass a function to it. Anything defined in that function is, of course, scoped to that function. Since it is scoped to that function, it is not a global. Your onclick attribute isn't defined in the scope of that function, it can only access globals. This is why you get a reference error.

    Avoid globals. They make things hard to maintain. Avoid onclick attributes, they usually depend on globals.

    You need to use ready if you want code to run after the DOM has been fully constructed. This is useful if you want to bind event handlers to elements in it with JS (e.g. with jQuery.on). Do this rather then using onclick attributes.

提交回复
热议问题