Doubt syntax initializing jQuery statement

1

I have a question with the initialization syntax of a jQuery statement. I mean ...

Using Dreamweaver I have seen that some of its versions (I do not know if all) when offering you the initialization code of a jQuery statement tell you the following:

$(document).ready(function(e){});

The point is that searching the Internet for recognized references, on the other hand, I find the following code:

$(document).ready(function(){});

The difference as you see is in the e that appears as a parameter in the function. I do not know exactly how important it is, or not, to define the function with parameter or without parameter, and if it is more correct to write it as Dreamweaver proposes or as I found in other Internet references.

    
asked by Hugo Sanchez 10.05.2016 в 10:38
source

3 answers

4

The difference lies in the use itself, sometimes you need to use a specific library that gives incompatibilities with the global object $ JQuery.

To be able to solve the reference $ with $.noConflict();

Then the only way to use the $ is getting the reference, with:

jQuery(document).ready(function(e){});

You can use the e or use $ so you should not change the code $..... existing, but if you need to have it within function() to refer to it.

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
   $.noConflict();
   jQuery( document ).ready(function( $ ) {
     // Código que se usa con JQUERY $
   });
   // Código Javascript que se usa con la otra librería
</script>

Extracted from the official JQuery documentation

    
answered by 10.05.2016 в 11:35
2

Yes, it makes sense. Many times you will find that you use other libraries together with jQuery, and that some of them use the $ symbol as alias.

It is a good practice, and highly recommended, to use the following syntax:

jQuery(document).ready(function($){
    // your code here...
});

$.otroMetodoDeOtraLibreria();

In this way, within the code encapsulated by the callback function that you pass to the ready event of jQuery, you can use the $ symbol with complete peace of mind, without overwriting other libraries and / or functionalities of your application.

    
answered by 10.05.2016 в 11:39
0

Really the first syntax does not make much sense.

jQuery does pass an argument to the function that is passed to the ready method, but it is the jQuery object itself (the same one that references the $ variable).

That's why it does not make much sense to reference it. That is, if with the second format you can do:

$(document).ready(function(){
    var element = $.find('#elementId');
});

In the first you could also do:

$(document).ready(function(e){
     var element = e.find('#elementId');
});

No more.

    
answered by 10.05.2016 в 10:58