JQuery Basics
(1) Basic concepts:
- Simplify js development
- Optimize HTML document operation, event processing, animation design and Ajax interaction
- JavaScript framework: the essence is some js files, which encapsulate the methods
(2) Quick start:
- Steps:
- Download JQuery file
- Import JQuery file
- Use file
- jquery-xxx.js and jQuery XXX Difference between min.js
- jquery-xxx.js development version: it is for programmers to see that it has good readability, good indentation and comments
- jquery-xxx.min.js production version: it is used in the program without indentation, and the volume is smaller,
(3) Basic grammar learning
-
1. Event binding
-
<script> $("#b1").click(function (){ alert("abc"); }); </script>
-
-
2. Entry function (page loading completion event)
-
<!-- window.onload : You can also perform loading actions But only one can be defined with this , If defined multiple times , The back will cover the front $(function(){ This method can be defined multiple times at the same time }); --> <script> $(function(){ }); </script>
-
-
3. Style control
-
<script> $(function(){ $("#div1").css("background-color","red"); }); </script>
-
(4) Difference and transformation between jQuery object and JS object
-
difference:
-
<!-- 1.JQuery Objects are more convenient to operate 2.JQuery Object and js Object methods are not generic 3.The two are converted to each other * JQuery- - -> js: jq object[Indexes] or jq object.get(Indexes) * js- - -> JQuery: $(js object) that will do -->
<script> //1. Get all element objects named div through js var divs = document.getElementsByTagName("div"); alert(divs); //[object HTMLCollection] //You can use it as an array //For all divs in divs, change their label content to aaa for (const div of divs) { div.innerHTML = "aaa"; } //2. Obtain all element objects with the name div through jq var $divs = $("div"); alert($divs); //[object Object] //It can also be used as an array //For all divs in $divs, change the label content into bbb, so there is no need to traverse $divs.html("bbb"); </script>
(5) Selector
- Filter elements (labels) with similar characteristics
1. Basic selector:
① Label selector: (element selector)
- $("html tag name"), get all elements matching the tag name
② id selector:
- $("#id attribute value"), gets the element matching the specified ID attribute value
③ Class selector:
- $("attribute value of. Class"), get the element matching the specified class attribute value
④ Union selector:
- $("selector 1, selector 2,..."): get all elements selected by multiple selectors
2. Level selector:
① Descendant selector:
- $("A B"): select all B elements inside the A element
② Sub selector:
- $("A > b"): select all B child elements inside the A element
3. Attribute selector:
① Attribute name selector:
- $("tag name [attribute name]"): the selector containing the specified attribute
② Attribute selector:
- $("tag name [attribute name = 'value']): contains a selector where the specified attribute is equal to the specified value
③ Composite attribute selector:
- $("tag name [attribute name = 'value'] [attribute name = 'value']..."): selector containing multiple attribute conditions
The attribute value starts with xx: (a ^ before the equal sign indicates the value starting with xx)
$("div[title ^= 'te']")
The attribute value ends with xx: (a $before the equal sign indicates the value ending with xx)
$("div[title $= 'est']")
Attributes with xx in the attribute value: (a * before the equal sign indicates attributes with xx)
$("div[title *= 'es']")
4. Filter selector:
① First element selector:
- Tag name: first gets the first element in the selected element
② Tail element selector:
- Tag name: last gets the last element in the selected element
③ Even selector:
- Tag name: even count from 0
④ Odd selector:
- Tag name: odd count from 0
⑤ Equal to index selector:
- Tag name: eq (index) specifies the index element
⑥ Greater than index selector:
- Tag name: gt (index) is greater than the specified index element
⑦ Less than index selector:
- Tag name: lt (index) is smaller than the specified index element
Note that the index here starts from 0,
⑧ Title selector:
- : header gets the title (h1~h6) element (fixed writing method)
⑨ Non element selector:
- Tag name: not() does not include the element of the specified content
5. Form filter selector:
① Available element selectors:
- Get available element: enabled
② Unavailable element selector:
- : disabled get unavailable elements
③ Select selector: (radio and multiple selection box)
- : checked gets the * * (selected) * * element in the radio check box
④ Select selector: (drop-down box)
- : selected get the * * (selected) * * element in the drop-down box
Note: the attribute that can be checked by setting the drop-down box is: the value of multiple attribute is multiple, so that multiple check boxes can be selected
(6)DOM operation
1. Content operation:
① html(): (tag body content)
- Gets or sets the label body content of the element
- obtain:
- Setting: also sets all contents under this element, including label contents
② text(): (plain text content)
- Gets or sets the plain text content of the label body of the element
- obtain:
- Setting: set all contents under this element, including label contents
③ Val(): (value attribute value)
- Gets or sets the value attribute value of the element
2. Attribute operation:
(1) General attribute operation
① attr(): get / set the attribute of the element
<script type="text/javascript"> $(function () { //Gets the name attribute value of the Beijing node var name = $("#bj").attr("name"); //Set the value of the name attribute of the Beijing node to dabeijing $("#bj").attr("name","dabeijing"); //The description attribute value of the new Beijing node is didu $("#bj").attr("discription","didu"); //Delete the name attribute of Beijing node and check whether the name attribute exists $("#bj").removeAttr("name"); //Get the selected status of hobby var checked = $("#hobby").prop("checked"); alert(checked); //var checked = $("#hobby").attr("checked"); // Unable to get, pop up undefined }); </script>
② removeAttr(): deletes the attribute of an element
③ prop(): get / set the attribute of the element
④ removeProp(): deletes the attribute of an element
- The difference between attr and prop
- If you operate on the inherent attributes of an element, prop is recommended
- If the operation is a custom attribute, attr is recommended
(2) Operation on class attribute
① addClass(): adds the class attribute value
② removeClass(): deletes the class attribute value
③ toggleClass(): toggles the class attribute value
- Add the attribute if it does not exist on the element object, and delete it if it exists
④ css(): you can also set the class attribute value
3. Operations of adding, deleting, modifying and querying: (CRUD)
① append(): the parent element appends the child element to the end
- Object 1 Append (object 2): add object 2 inside the element of object 1 and at the end
② prepend(): the parent element adds the child element to the beginning
- Object 1 Prepend (object 2): add object 2 to the inside of the object 1 element and start at the beginning
③ appendTo(): add object 1 to the internal end of object 2
- Object 1 Appendto (object 2)
④ prependTo(): add object 1 to the beginning of object 2
- Object 1 Prependto (object 2)
⑤ after(): add element to the back of element
- Object 1 After: add object 2 to the back of object 1. Object 1 and object 2 are brothers
⑥ before() :
- Object 1 After: add object 2 to the front of object 1. Object 1 and object 2 are brothers
⑦ insertAfter() :
- Object 1 Insertafter: adds object 1 to the back of object 2
⑧ insertBefore() ;
- Object 1 InsertBefore (object 2): adds object 1 to the front of object 2
⑨ Remove(): remove element
- Object remove(): delete the object
⑩ empty(): clears all descendant elements of the element
- Object empty(): empty all the descendant elements of the object However, the current object and its attribute nodes are preserved
⑩ ① clone (): clone the matching DOM elements and select the copies of these clones
(7) Case
Select all or deselect all:
function selectAll(obj){ //Get the check box at the bottom and add an attribute to them. The value is the value of the all selection box at the top $(".itemSelect").prop("checked",obj.checked); }
qq expression:
//Demand: click qq expression to add it to the speech box $(function () { //1. Add onclick event to img image $("ul img").click(function(){ //2. Add it to the p tag. $(".word").append($(this).clone()); }); });
Multi selection drop-down list moves left and right
$(function () { //toRight $("#toRight").click(function () { //Get the drop-down list object on the right, append (option selected in the drop-down list on the left) $("#rightName").append($("#leftName > option:selected")); }); //toLeft $("#toLeft").click(function () { //appendTo gets the option selected on the right and moves it to the drop-down list on the left $("#rightName > option:selected").appendTo($("#leftName")); }); });
JQuery advanced features:
(1) Animation
1. Show and hide elements in three ways
Parameters:
- Speed: the speed of the animation, three predefined values,
- ("slow", "normal", "fast") or millisecond value indicating the duration of animation (e.g. 1000);
- easing: used to specify the switching effect of animation. The default is "swing". The parameter "linear" can be used. (this value can not be passed)
- swing: when the animation is executed, slow first, fast in the middle, and slow last
- linear: execute animation at a constant speed
- This value can't be passed to FN}
① Default display and hide mode:
- Show ([speed, [easing], [FN]])
- Hide ([speed, [easing], [FN]) (hidden)
- Toggle ([speed, [easing], [FN]])
② Sliding display and hiding mode: (sliding up and down)
- Slidedown ([speed, [eating], [FN]) (display)
- Slideup ([speed, [easing], [FN]) (hidden)
- Slidetoggle ([speed, [easing], [FN]) (SWITCHING)
③ Fade in and fade out display and hide methods:
- Fadein ([speed, [easing], [FN]) (display)
- Fadeout ([speed, [easing], [FN]) (hidden)
- Fadetoggle ([speed, [easing], [FN]) (SWITCHING)
(2) Traversal mode
-
Traversal mode of js
- for (initial value; cycle end condition; step size)
-
Traversal mode of jq:
① jq object each(callback)
-
var citys = $("#city li"). citys.each(function (index , element){ //The first method is to get the li object and use this alert(this.innerHTML); //The second method is to get the li object and define parameters in the callback function, such as index and element alert(index + ":" + element.innerHTML); });
-
Case: if you want to add some judgment conditions to the cycle:
if("Shanghai" == $(element).html){ //If the current function returns false, the loop (break) is ended //If the current return is true, this cycle will be ended and the next cycle will continue return false; }
② JQuery.each( object , [ callback ] ) // $.each ( object , [ callback ])
-
$.each(citys , function(){ });
③ for . . of
-
//Methods provided by jQuery versions after 3.0: for ( li of citys ){ }
(3) Event binding
JQuery can use chain programming to simplify the writing of binding:
jq object.Event function(Callback function(){}).Event function(Callback function(){}).Event function(Callback function(){})....
Let the text box get the focus event:
jq object.focus ( ) ; //Get the object (text box) in focus //If the callback function is not passed inside, the browser will trigger the default event mode
Form submission:
jq object.submit() ; //Form submission
1.JQuery standard binding method:
- jq object Event function (callback function)
2.on bind event / off unbind
- jq object on("event name", callback function)
- jq object off("event name")
- If the event name is not written, all events on the object will be unbound
3. Event switching: toggle
- jq object toggle ( fn1 , fn2 . . .)
- When you click Fnq to execute all the new components for the second time, it will execute from fn1 to Fnq
(4) Case
Advertisement pop-up window:
//Define entry function $(function(){ //Set the timer and call the adShow method setTimeout(adShow , 3000); //Set the timer and call the ad close method adHide setTimeout(adHide , 8000); }); //Display advertisement function adShow(){ //Get the advertisement div and call the display method $("#ad").show("slow"); }; //Hidden advertising function adHide(){ //Get the advertisement div and call the hidden method $("#ad").hide("slow"); }; //Note that you should first set a style for the div of the advertisement: display: none,
Lucky draw cases:
-
analysis:
-
① Bind click event to start button
-
1.1 define the cycle timer,
-
1.2 switch src attribute of small photo frame,
- Define an array to store image resources
- Generate random number, array index
-
② Bind click event to end button
-
1.1 stop timer
-
1.2 set src attribute for large photo frame
-
var imgs = ["../img_01.png" , "../img_02.png" , "../img_03.png" , "../img_04.png"...] var startId ; var index ; $(function(){ //Bind a click event to the start button $("#startID").click(function(){ //Define the cycle timer: execute every 20 milliseconds startId = setInterval(function(){ //Generate random footmark: 0-3 index = Math.floor(Math.random()); // Number between 0.000 -- 0.999 -- > * 3 = = > 0.000 -- 2.999 (math. Floor(): round down) //Set the src attribute of the small photo frame, $("#img1ID").prop("src" , imgs[index]); } , 20); }); //Bind a click event to the end button $("#stopID").click(function(){ //Stop timer: clearInterval(startId); //Set src attribute for large photo frame $("img2ID").prop("src" , imgs[index]) }); });
(5) Plug in:
Enhance the function of JQuery
-
JQuery . fn . Extend (object): enhance the function of objects obtained through jQuery
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery Object for method extension</title> <script src="js/jquery-3.3.1.min.js" type="text/javascript" charset="UTF-8"></script> <script> //Use the JQuery plug-in to add two methods to jq objects. check() selects all check boxes and uncheck() deselects all check boxes //1. Define the plug-in of JQuery object $.fn.extend({ //The check() method is defined, and all jq objects can call this method check: function () { //Leave the check box selected //this: the jq object that calls the method this.prop("checked", true); }, //Separated by uncheck: function () { //Leave the check box unchecked this.prop("checked", false); } }); $(function () { $("#btn-check").click(function () { //attribute selectors $("input[type='checkbox']").check(); }); $("#btn-uncheck").click(function () { $("input[type = 'checkbox']").uncheck(); }); }); </script> </head> <body> <input id="btn-check" type="button" value="Click to select the check box" onclick="checkFn()"> <input id="btn-uncheck" type="button" value="Click to select the check box" onclick="uncheckFn()"> <br> <input type="checkbox" value="football">Football <input type="checkbox" value="basketball">blue ball <input type="checkbox" value="volleyball">Volleyball </body> </html>
-
-
JQuery . Extend (object): enhance the function of jQuery object itself
-
<script> $.extend({ max:function(a,b){ return a>b ? a : b ; } min:function(a,b){ return a<b ? a : b ; } }); var max = $.max(10 , 5); </script>