Appearance
jQuery
You may have heard of jQuery. Despite its somewhat outdated name, it is the most widely used library in the JavaScript world.
It is rumored that about 80-90% of websites worldwide use jQuery either directly or indirectly. Given its popularity and ease of use, every beginner JavaScript front-end engineer should understand and learn it.
jQuery's popularity is due to its ability to solve some important problems. In fact, jQuery can help us with the following:
- Eliminate browser differences: You don't need to write lengthy code to bind events or write AJAX code for different browsers.
- Simplified DOM manipulation: Writing
$('#test')
is definitely simpler thandocument.getElementById('test')
. - Easily implement animations, modify CSS, and perform various operations.
The philosophy of jQuery, "Write Less, Do More," allows you to write less code and accomplish more!
jQuery Versions
You can download the latest version from the jQuery official website. jQuery is just a single jquery-xxx.js
file, but you will see both compressed and uncompressed versions. They are functionally identical, but if you want to study the jQuery source code in depth, you should use the uncompressed version.
Using jQuery
To use jQuery, you only need to include the jQuery file in the <head>
of your page:
html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
...
</head>
<body>
...
</body>
</html>
The good news is that when you are learning this tutorial, jQuery is already included, so you can use it directly:
javascript
console.log('jQuery version: ' + $.fn.jquery);
The $ Symbol
The $
symbol is famous in jQuery. In fact, jQuery wraps all functionality within a global variable called jQuery
, and $
is also a valid variable name, serving as an alias for jQuery
:
javascript
window.jQuery; // jQuery(selector, context)
window.$; // jQuery(selector, context)
$ === jQuery; // true
typeof($); // 'function'
The $
is essentially a function, but since functions are also objects, $
can have many other properties in addition to being directly callable.
Note that the $
function name you see may not be jQuery(selector, context)
, as many JavaScript minification tools can rename function names and parameters, so the minified jQuery source code may turn $
into a(b,c)
.
Most of the time, we directly use $
(because it's simpler). However, if the $
variable happens to be taken and cannot be changed, we can make jQuery relinquish the $
variable, and we will only be able to use the jQuery
variable:
javascript
$; // jQuery(selector, context)
jQuery.noConflict();
$; // undefined
jQuery; // jQuery(selector, context)
The magic behind this is that jQuery saves the original $
before taking it, and calling jQuery.noConflict()
restores the original variable.