1, Introduction to JQuery
(1) Introduction
JQuery is a fast and concise JavaScript framework. The purpose of jQuery design is "write Less, Do More", which advocates writing less code and doing more things. It encapsulates the common functional code of JavaScript, provides a simple JavaScript Design pattern, and optimizes HTML document operation, event processing, animation design and Ajax interaction.
(2) Use
1. Introduce
In the previous JavaScript course, we talked about the introduction of external js files, as follows:
<script src="./js/jquery-3.3.1.min.js" type="text/javascript"></script>
2. Use
In jQuery, the identifier $is equivalent to jQuery, that is, jQuery = = $. For simplicity and convenience, we usually use $instead of jQuery. But jQuery is strictly case sensitive.
For example, we can find elements through jQuery (selector) or $(selector).
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Jquery Use of</title> </head> <script src="./js/jquery-3.3.1.min.js" type="text/javascript"></script> <script> $(function() { console.log($("div").html()); }); </script> <body> <div>Hello Jquery</div> </body> </html>
2, Page loading
jQuery provides the ready() function, which is used to execute after the page is loaded successfully. Consistent with the window.onload function. There are three ways to write:
Code example:
$(function(){ alert(3); })
The difference between JQuery's ready() and window.onload:
1. Different execution time
window.onload cannot be executed until all elements including pictures in the page are loaded.
$ (document).ready() is executed after the DOM structure is drawn. You don't have to wait until the loading is completed.
It can be seen that the execution time of $(document).ready() is earlier than window.onload.
2. The number of preparation is different
Multiple windows.onload cannot be written at the same time. If there are multiple windows.onload, only one will be executed.
$ (document).ready() can write multiple at the same time and can be executed.
3. Simplified writing
There is no simplified writing method for window.onload.
$ (document).ready(function() {}) can be abbreviated as $(function() {});
3, js object and jQuery object
(js object) DOM object: the object obtained through the native JavaScript method is the DOM object.
JQuery object: it is the object generated after wrapping DOM objects through jQuery.
jQuery objects and DOM objects can be converted to each other, but remember that the properties and functions of the two objects cannot be mixed and used with each other
DOM object to jQuery object, syntax: jQuery(DOM object); Or $(DOM object);
JQuery object to DOM object, syntax: jQuery object [index]; Or jQuery object. get(index);
Code example 1:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js" type="text/javascript"></script> <script> $(function(){ var obj = document.getElementsByTagName("div")[0]; console.log(obj.innerHTML); console.log($("div").html()); console.log($(obj).html()); $obj = $("div"); console.log($obj[0].innerHTML); }) </script> </head> <body> <div>div Area label <a href="">use Baidu Search</a> </div> </body> </html>
4, jQuery selector
JQuery selector is a powerful embodiment of jQuery. It provides a set of methods to make it easier for us to get the elements in the page. JQuery selector inherits part of the syntax of CSS and Path language, and allows fast and accurate positioning of DOM elements through tag name, attribute name or content, so as to complete the processing of element attributes and behaviors.
Classification of jQuery selectors:
1. Basic selector
2. Level selector
3. Attribute selector
4. Filter selector
5. Form selector
(1) Basic selector
The basic selector is the one we use most frequently.
It mainly includes: label selector, ID selector and class selector.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js" type="text/javascript"></script> <script> $(function(){ $arr = $("p"); for(var i = 0;i<$arr.length;i++){ console.log($arr[i].innerHTML); } $obj = $(".first"); for(var i = 0;i<$obj.length;i++){ console.log($obj[i].innerHTML); } console.log($("#title").html()); }) </script> </head> <body> <p id = "title" class="first">I am p label</p> <p class="first">I am p </p> <p>I am p3</p> </body> </html>
(2) Level selector
Level selector refers to obtaining elements according to the hierarchical relationship of the node tree. Generally speaking, it is the relationship between descendant elements / parent-child elements / brother elements.
It mainly includes: descendant selector and sub selector.
1. Descendant selector: parent child, separated by spaces. Get all sons, grandchildren... Elements inside the parent element. (grandparent relationship)
2. Sub selectors: parent > child, separated by the > symbol. Gets the child element below the parent element. (parent-child relationship)
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $arr = $("#main span"); for(var i=0;i<$arr.length;i++){ console.log($arr[i].innerHTML); } $arr.each(function(i,dom){ console.log(dom.innerHTML); console.log($(dom).html()); }) }) </script> </head> <body> <div id="main"> <p> I am a p in div</p> <span>i am a span in div</span> <p> <span>I am a span in p</span> </p> </div> <div> <span>hahahahahha</span> </div> </body> </html>
(3) Attribute selector
Filter by attribute or attribute value.
[attribute] $("[href]") all elements with a href attribute
[attribute=value] $("[href = '#']") all elements whose href attribute value is equal to "#"
[attribute=value] [attribute=value] $("[href='#'][class='demo ']) the value of all href attributes is equal to" # ", and the value of class attribute is" demo "
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $arr = $("[href]"); $arr.each(function(i,dom){ console.log(dom.innerHTML); }); $obj = $("[href='regist.html']"); console.log($obj.html()); }) </script> </head> <body> <a href="index.html">Link 1</a> <a href="login.html">Link 2</a> <a href="regist.html">Link 3</a> <a href=""></a> <a href=""></a> </body> </html>
(4) Filter selector
The filter selector is to filter the desired elements again from the obtained object list. Common filter selectors are:
: First first
: Last last
: eq(index) specifies the of the index
: gt(index) is greater than the of the index
: lt(index) is less than the of the index
: odd number
: even number
: not() except**
: header matches the title, such as h2,h3
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ //:first console.log($("ul li:first").html()); //:last console.log($("ul li:last").html()); //:eq(index) console.log($("ul li:eq(1)").html()); console.log("============================"); //:lt(index) $arr = $("ul li:lt(3)"); $arr.each(function(i,dom){ console.log(dom.innerHTML); }) //:gt(index) $arr4 = $("ul li:gt(1)") $arr4.each(function(i,dom){ console.log(dom.innerHTML); }) console.log("============================"); //:odd $arr1 = $("ul li:odd"); $arr1.each(function(i,dom){ console.log(dom.innerHTML); }) //:even $arr3 = $("ul li:even"); $arr3.each(function(i,dom){ console.log(dom.innerHTML); }) console.log("============================"); //:header $arr2 = $("body :header"); $arr2.each(function(i,dom){ console.log(dom.innerHTML); }) }) </script> </head> <body> <h1>H1 title</h1> <h2>H2 title</h2> <ul> <li>one</li> <li>two</li> <li>three</li> <li>four</li> </ul> <h3>H3 title</h3> </body> </html>
(5) Form selector
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $obj = $("body :disabled"); console.log($obj.val()); $arr= $("body :enabled"); $arr.each(function(i,dom){ console.log(dom.value); }) $("#btn").click(function(){ $arr1 = $("input[type='checkbox']:checked"); $arr1.each(function(i,dom){ console.log(dom.value); }) $arr2 = $(":selected"); console.log($arr2.val()); }) $("#txt").blur(function(){ console.log($(this).val()); }) $("#d1").change(function(){ console.log(this.value); }) }) </script> </head> <body> sex: man:<input type="radio" name="sex" value="man" id="" disabled> women:<input type="radio" name="sex" value="woman" id=""><br> hobby: smoking:<input type="checkbox" name="hobby" value="smoking" id=""> tang:<input type="checkbox" name="hobby" value="tang" id=""> walk:<input type="checkbox" name="hobby" value="walk" id=""><br> <select name="" id="d1"> <option value="bj">bj</option> <option value="sh">sh</option> <option value="nj">nj</option> </select> <input type="button" value="click" id = "btn"> <input type="text" name="" id="txt"> </body> </html>
5, DOM operation of jQuery
(1) Attribute operation
attr()
attr("attribute name") gets the value of the corresponding attribute name in the tag
attr("attribute name", "attribute value") sets the attribute name of the label and the corresponding attribute value
prop()
prop("attribute name") gets the value of the corresponding attribute name in the tag
prop("attribute name", "attribute value") sets the attribute name of the label and the corresponding attribute value
What is the difference between attr() and prop()?
attr() can operate the self-contained and user-defined attributes in the tag, but there is a function failure problem in some use processes
prop() implements the operation of the attributes in the tag. It is recommended
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .c2{ border: 2px solid red; } </style> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ console.log($("#txt").attr("name")); console.log($("#txt").prop("name")); console.log($("#txt").attr("ids")); console.log($("#txt").prop("ids")); $("#txt").prop("class","c2"); }) </script> </head> <body> <input type="text" id="txt" name="username" ids="hello" class="c1"> </body> </html>
(2) class operation
1. addClass() adds one or more classes to the selected element
2. removeClass() Deletes one or more classes from the selected element
3. toggleClass() switches between adding and deleting classes for the selected element
Example code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ border: 1px solid orange; height: 100px; width: 100px; } .c1{ border: 1px solid red; height: 300px; } .c2{ width: 400px; background-color: blue; } .c3{ background-color: springgreen; } </style> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $("div").mouseover(function(){ $(this).addClass("c1 c2"); }) $("div").mouseout(function(){ $(this).removeClass("c2"); }) $("div").click(function(){ $(this).toggleClass("c3"); }) }) </script> </head> <body> <div>Area label</div> </body> </html>
(3) Content operation
1. html() sets or returns the content of the selected element (including HTML tags)
2. text() sets or returns the text content of the selected element
3. val() sets or returns the value of the form field
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./js/jquery-3.3.1.min.js"></script> <script> $(function() { $("#btn").click(function() { console.log($("div").html()); //Get the contents of div console.log($("div").text()); //Get the text content of div console.log($("#d1").val()); / / get the value entered in the text box }); }) </script> </head> <body> <div> <a href="">Hyperlinks-use Baidu Search</a> </div> <input type="text" id="d1" /> <br> <input type="button" value="click" id="btn"> </body> </html>
(4) Style operation
1. css("style name") gets the value of the style
2. css("style name", "value") sets a style
3. css({style name ":" value "," style name ":" value ",...}) sets multiple styles
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $("#btn").click(function(){ $("div").css({"height":"200px","width":"200px","border":"1px solid red"}) }) }) </script> </head> <body> <div></div> <input type="button" value="click" id="btn"> </body> </html>
(5) Document operation
1. Internal insertion
1. append(); insert content at the end of the selected element
2. prepend(); insert content at the beginning of the selected element
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $("#btn1").click(function(){ $("ul").append("<a href=''>use Baidu Search</a>") $("ul").prepend("<a href=''>use Baidu Search</a>") }) $("#btn2").click(function(){ }) }) </script> </head> <body> <ul> <li>one</li> <li>two</li> <li>three</li> </ul> <input type="button" value="Internal addition" id="btn1"> <input type="button" value="External addition" id="btn2"> <input type="button" value=""> </body> </html>
2. External insertion
1. after(); insert content after the selected element
2. before(); insert content before the selected element
3. Delete
1. empty(); empty the contents
2. remove(); delete the entire element
3. detach(); delete the entire element
2. The difference between deletion and deletion is that the deletion of detach is still left on the page and does not completely disappear
6, jQuery event
The event type of jQuery is basically the same as the JavaScript event type we learned before, but there are some differences in the use methods, such as click event, out of focus event blur, focus event focus, etc
Code examples are as follows:
$obj.click(function(){
// Write the js code to be executed after the click event is triggered
});
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./js/jquery-3.3.1.min.js"></script> <script> $(function() { //Add click event to button $("#btn").click(function() { alert("Button click event triggered and executed"); }); }) </script> </head> <body> <input type="button" value="Click event demo" id="btn"> </body> </html>
7, Animation effect
1. Show and hide
JQuery special effect refers to that jQuery encapsulates some good-looking effects of JS for handling the display and hiding of elements, which can be used directly by calling functions.
Common jQuery effects are as follows:
1. Display and hide
(1) show(speed,callback); display elements.
(2) hide(speed,callback); hide elements.
(3) toggle(speed,callback); switch between show() and hide() methods to display the hidden elements and hide the displayed elements.
Parameter Description:
The speed parameter specifies the speed of hiding and displaying, and can take the following values: "slow", "fast" or milliseconds.
The callback parameter hides or displays the name of the callback function executed after completion.
Both of the above parameters are optional.
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width: 100px; height: 100px; background-color: brown; } </style> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $("#btn1").click(function(){ $("div").hide(5000,function(){ alert("Hey, hey, hey, hey") }) }) $("#btn2").click(function(){ $("div").show(5000,function(){ alert("Big big big") }) }) $("#btn3").click(function(){ $("div").toggle(3000) }) }) </script> </head> <body> <div>12</div> <input type="button" value="hide" id="btn1"> <input type="button" value="display" id="btn2"> <input type="button" value="hide/show" id="btn3"> </body> </html>
2. Fade in and out
(1) fadeIn(speed,callback); fade in hidden elements.
(2) fadeOut(speed,callback); fades out visible elements.
(3) fadeToggle(speed,callback); switches between fadeIn() and fadeOut() methods. If the element is faded out, fadeToggle() adds a fade in effect to the element. If the element is faded out, fadeToggle() adds a fade out effect to the element.
The function of parameters is the same as above.
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width: 100px; height: 100px; background-color: brown; } </style> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $("#btn1").click(function(){ $("div").fadeIn(5000,function(){ alert("Hey, hey, hey, hey") }) }) $("#btn2").click(function(){ $("div").fadeOut(5000,function(){ alert("Big big big") }) }) }) </script> </head> <body> <div>12</div> <input type="button" value="hide" id="btn1"> <input type="button" value="display" id="btn2"> <input type="button" value="hide/show" id="btn3"> </body> </html>
3. Sliding effect
(1) Slide down (speed, callback); slide down the element for display.
(2) slideUp(speed,callback); slide the element upward for hiding.
(3) slideToggle(speed,callback); switches between slideDown() and slideUp() methods. If the elements have slid down, slideToggle() slides them up. If the elements have slid up, slideToggle() slides them down.
The function of parameters is the same as above.
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ border:1px solid black; width: 200px; height: 200px; } #a { background-color: brown; } </style> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $("#btn1").click(function(){ $("#a").slideUp(5000,function(){ alert("Hey, hey, hey, hey") }) }) $("#btn2").click(function(){ $("#a").slideDown(5000,function(){ alert("Big big big") }) }) }) </script> </head> <body> <div> <div id="a">12</div> </div> <input type="button" value="hide" id="btn1"> <input type="button" value="display" id="btn2"> <input type="button" value="hide/show" id="btn3"> </body> </html>
4. Custom animation
Functions for creating custom animations.
The key of this function is to specify the animation form and result style attribute object. Each attribute in this object represents a variable style attribute (such as "height", "top" or "opacity"). Note: all specified attributes must be in camel form, such as using marginLeft instead of margin left
animate(params,[speed],[fn])
Parameter resolution:
1.params: a set of style attributes and their values as animation attributes and end values
2.speed: a string ("slow","normal", or "fast") representing one of the three predetermined speeds or a millisecond value representing the animation duration (e.g. 1000)
3.fn: the function to be executed when the animation is completed. Each element is executed once.
Code example:
8, Array operation
jQuery has its own methods for traversing objects or arrays, as follows:
The first way to write:
$obj.each(function(i,dom){
});
The second way to write:
$.each(object,function(i,dom){
});
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width: 50px; height: 50px; background-color: red; position: absolute; } </style> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $("div").click(function(){ $(this).animate({"left":"500px"},5000,function(){ $(this).hide(3000) }) }) }) </script> </head> <body> <div>12</div> </body> </html>
i: the index of the member or array of the object
dom: corresponding variable or content, which is a js object
Note: if you need to exit each loop, the callback function can return false, and other return values will be ignored.
Code example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="js/jquery-3.6.0.min.js"></script> <script> $(function(){ $arr = $("div") $arr.each(function(i,dom){ console.log($(dom).html()); }) }) </script> </head> <body> <div>123</div> <div>321</div> </body> </html>
9, Form plug-in
When learning javascript, we manually complete the verification of form data. This function is also common in actual development and belongs to a general function. However, if we simply verify through javascript, we still have too many options. In fact, we all use third-party tools in development. In this case, we will use jQuery plug-in validation Verify the form.
Usage steps of validation plug-in:
1. Download the validation tool.
2. Import tools jquery-3.4.1.js, jquery.validate.js, messages_zh.js.
3. Write the form information and bind the validate validation method to the form in the script.
4. Specify the validation rules one by one in the form elements.