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

前端 未结 2 742
悲哀的现实
悲哀的现实 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:25

    A lot of what you're seeing is because of jsFiddle's very surprising default setting, which is to wrap the code in the script pane in an onload handler. So your code is wrapped in a function and no longer at global scope (which is where functions need to be if you use onclick-style attributes). You can change this with the drop-down box on the left (the second one, under the list of libraries and scripts). Change it to "no wrap" to have unwrapped code.

    You're not (by far!) the first to be bit by this surprising default.


    Answering your main question:

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

    If you control where the script tags loading your script go, you basically never have to use ready; instead, just make sure your script tags are at the end of the HTML, just before the closing .

    You can use ready, of course. The reason for doing so is to make sure that all the DOM elements have been created before your code runs. But if you put your script tag at the end, that's already true. You can still define your functions outside of the ready handler (if you want them to be globals), but if you're using ready, you would call them from the ready handler so the elements exist.


    FWIW, I would avoid using onclick-style attributes for hooking up event handlers, primarily because they require you to create global functions. I prefer to avoid creating any global symbols when I can avoid it.

    The general form I'd recommend:

    
    
    
    
    
    

    where your script looks like this:

    (function($) { // A scoping function that wraps everything
        // Hook up event handlers here. You can use `$` for jQuery, even if
        // you've used noConflict, because we have a private `$` symbol (see
        // the `$` argument above)
    
        // The body of your code goes here
    
    })(jQuery); // <== Note how we're passing the jQuery reference in
                // and immediately executing the scoping function
    

    Here's a complete example: Live Copy

    
    
    
    
    Script Placement Example
    
    
      
      
      
    
    
    

提交回复
热议问题