Java full stack web page technology: 4 jQuery

Chapter 1: introduction to jQuery

  • In order to simplify the development of JavaScript, some JavsScript libraries were born. JavaScript library encapsulates many predefined objects and practical functions, simplifies the operation between HTML and JavaScript, helps users create pages with difficult interaction, and is compatible with major browsers.

  • The current popular JavaScript libraries are

  • JQuery is another excellent JavaScript framework after prototype. Nowadays, * * jQuery has become the most popular JavaScript library** More than 55% of the world's top 10000 most visited websites use jQuery.
  • jQuery, as its name implies, is JavaScript and Query. Its purpose is * * "WRITE LESS, DO MORE" * *, which greatly simplifies JavaScript developers to traverse HTML documents, operate DOM, handle events, execute animation and develop Ajax. Specifically, the advantages are as follows:
    • jQuery is free and open source
    • Lightweight (only tens of k after compression)
    • Powerful selector
    • Excellent encapsulation of DOM operations
    • Reliable event handling mechanism
    • Perfect Ajax usage
    • Excellent multi browser compatibility
    • Implicit iteration: when doing the same operation on collection objects, jQuery does not need to traverse one by one, and jQuery automatically traverses
    • The documentation is very complete
    • Extensible plug-in

Chapter 2: getting started with jQuery

2.1 add the library file of jQuery to the application

  • The jQuery library is actually a js file. You just need to import this file directly into the web page.
  • Add jQuery's library file to
    • The test was developed using an uncompressed version: jquery-1.7 2.js

    • In the online project, the compressed version: jquery-1.7.0 will be used 2.min. js

2.2 HelloWorld

  • Requirement: use jQuery to bind a click event to a button
<!-- Import jQuery library-->
<script type="text/javascript" src="script/jquery-1.7.2.js"></script>
<script type="text/javascript">
    //Call the function defined by the jQuery library
    //Use $() instead of window onload
	$(function(){
    	//Get the button object according to the id attribute and bind the click response function
		$("#btnId").click(function(){
            //Pop up HelloWorld
			alert("HelloWorld");
		});
	});
</script>

<button id="btnId">ClickMe</button>
  • common problem?

    • Is it necessary to introduce the jquery library when using jquery?

      Answer: Yes, it must be introduced first

    • What exactly is $in jquery?

      Answer: it is a function name, which is the core function of jQuery. alert($)

    • How to add a click response function for a button?

      answer:

      1. First, after the page is loaded

      2. Find label objects

      3. Object by label click(function() {}) binding event

Chapter 3: jQuery basic syntax

3.1 initial analysis of jQuery source code

(function( window, undefined ) {	//16 lines
	
	var jQuery = (function() {	//Line 22
	
		var jQuery = function( selector, context ) {
			// The jQuery object is actually just the init constructor 'enhanced'
			return new jQuery.fn.init( selector, context, rootjQuery );
		};
		
		jQuery.fn = jQuery.prototype = {	//Line 97
			constructor: jQuery,
			init: function( selector, context, rootjQuery ) {
				//...
			}	//Line 207
			
		};	//Line 319
	
		//...
		return jQuery;	//Line 981

	})();	//Line 983
	
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;	//Line 9384
	
})( window );	//Line 9404

explain:

  • Self executing function
  • Two equivalent functions are added to window: jQuery() / $()
  • After $() is executed, an object wrapped in jQuery library is returned, which is generally called jQuery object
  • $is a jQuery object, and jQuery is a function reference
  • $(): call jQuery() function

3.2 jQuery core function: $()

  • The jQuery library defines a function for the window object: jQuery(), which is simplified to: $()
  • yes j Q u e r y of nucleus heart letter number , ∗ ∗ j Q u e r y of nucleus heart Merit can all yes through too this individual letter number real present . ∗ ∗ Is the core function of jQuery, * * the core functions of jQuery are realized through this function** Is the core function of jQuery, * the core functions of jQuery are realized through this function. * * () calls the $function.
  • The $function will do different work according to different parameter data types, and return an object of pseudo array encapsulated by jQuery
  • The core function has the following four functions:
    • When the passed in parameter is a function: $(function() {})
    • When the passed in parameter is a selector string: $(selector string)
    • When the incoming parameter is an HTML string: $(HTML string)
    • When the passed in parameter is a DOM object: $(DOM object)

3.2. 1 when the passed in parameter is a function: $(function() {})

  • Pass in a function parameter as the callback function. Equivalent to window onload = function(){}
  • Indicates that the callback function is automatically executed after the DOM document is loaded
  • This function is $(document) Short form of ready (function() {}). (see jQuery document - events - page loading)
  • It works with window Onload is different

  • Source focus

3.2. 2 when the incoming parameter is a selector string: $(selector string)

  • Receives a string parameter in CSS selector format

  • Find the element node object based on this selector

  • Match a set of elements in the document according to this string, and encapsulate it into a jQuery object to return

  • give an example:

    $("#id attribute value "); it is equivalent to finding the label object through the id attribute
    $("Tag name");  It is equivalent to finding the label object by the label name and returning the collection
    $(".class Attribute value");  Equivalent to passing class Property to find the label object and return the collection
    
  • Source focus




3.2.3 when the incoming parameter is HTML string: $(HTML string)

  • Receive a label string parameter.

  • Create an element node object from this html string

  • Create the corresponding label object and wrap it into a jQuery object

  • Code example:

    var $liEle = $("<li>Hong Kong</li>") //It is equivalent to creating a label object < li > Hong Kong < / Li >.
    $("#city").append($liEle); // Add this jQuery object to the jQuery object with id city.
    //amount to:
    var liObj = document.createElement("li");//<li></li>
    liObj.innerHTML = "Hong Kong"; //<li>Hong Kong</li>
    document.getElementById("city").appendChlid(liObj);
    
    <body>
    	<ul id="city">
    		<li id="bj">Beijing</li>
    		<li>Shanghai</li>
    		<li>Tokyo</li>
    		<li>Seoul</li>
    	</ul>
    </body>
    

3.2. 4 when the passed in parameter is a DOM object: $(DOM object)

  • Receive a parameter of DOM object type

  • Returns the jQuery object containing the DOM object. It is equivalent to wrapping (or converting) DOM objects into jQuery objects.

    • Note: if you declare a variable to point to a jQuery object, the variable naming convention should start with $. This is the naming convention for jQuery objects.
  • Code example

    var bjEle = document.getElementById("bj");
    alert(bjEle);
    alert($(bjEle));
    
  • Source focus

3.3 distinction between jQuery object and DOM object

3.3. 1 what are DOM objects and jQuery objects

  • DOM object: the element object found through the DOM standard implemented by native js
  1. The tag object queried through getElementById() is a Dom object

  2. The tag object queried through getElementsByName() is a Dom object

  3. The tag object queried through getElementsByTagName() is a Dom object

  4. The object created by the createElement() method is a Dom object

  • jQuery object: find or wrap the object through $
  1. The objects queried through the API provided by jQuery are jQuery objects. For example: 3.2 2
  2. The object created through the API provided by jQuery is a jQuery object. For example: 3.2 3. Situation
  3. DOM objects wrapped by jQuery are also jQuery objects. For example: 3.2 4

3.3. 2. Essence of jQuery object

  • JQuery object is essentially a structure that encapsulates DOM object array and a series of jQuery function functions.

  • Traditionally, when naming jQuery objects, the variable name is preceded by $, which is convenient to distinguish jQuery objects from js DOM objects.

  • Test code:

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript" src="../script/jquery-1.7.2.js"></script>
        <script type="text/javascript">
    
            $(function(){
                var arr = [12,"abc",true];
                var $btnObjs = $("button");
                alert("111");
                for(var i = 0;i < $btnObjs.length;i++){
                    alert($btnObjs[i]);
                }
            });
    
    
        </script>
    </head>
    <body>
    
    	<button id="btn">Button</button>
    	<button id="btn2">Button</button>
    	<button id="btn3">Button</button>
    
    </body>
    
  • Source code analysis:

3.3. 3. Differences between jQuery objects and DOM objects

  • The properties of jQuery object and DOM object cannot be used with each other, and only the declared properties can be called.
  • The functions of jQuery object and DOM object cannot be used with each other, and only the declared functions can be called.
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Insert title here</title>
	<script type="text/javascript" src="../script/jquery-1.7.2.js"></script>
	<script type="text/javascript">
		
		$(function(){
		   alert(document.getElementById("testDiv").innerHTML);
			//The properties of jQuery object and DOM object cannot be used with each other. The following call is wrong.
		   alert($("#testDiv").innerHTML);
			
		   alert(document.getElementById("testDiv").getElementsByTagName("span")[0]);
			//The functions of jQuery object and DOM object cannot be used with each other. The following call is wrong.
		   alert($("#testDiv").getElementsByTagName("span")[0]);
		});
	</script>
</head>

<body>
	<div id="testDiv">Atguigu is <span>100%</span> Very Good!</div>
</body>

3.3. 4. Mutual conversion of DOM object and jQuery object (Master)

  • DOM object to jQuery object
    • Wrapping DOM objects with jQuery core functions: $(DOM objects)
    • For example: var $btnEle = $(btnEle)
  • jQuery object to DOM object
    • Use array subscript: $btnEle[0]
    • Use the get(index) method: $btnele get(0)

  • Why do we need to convert the two? Analogy: why does java talk about the conversion between arrays and collections
    • DOM object to jQuery object: to call the rich methods provided by jQuery
    • jQuery object to DOM object: some special requirements are not provided in the framework, and the native js implementation is required

3.3.5 DOM object and jQuery object exercise

Requirements:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DOM Object and jQuery object</title>
	<script type="text/javascript" src="../script/jquery-1.7.2.js"></script>
	<script type="text/javascript">
		// 1. Use DOM object to call DOM method
		$(function () {
			$("#dom2dom").click(function () {
				var ele1 = document.getElementById("testDiv") // Get DOM object
				alert(ele1.innerText) // Get text from DOM object
			})
		})

		// 2. Call jQuery method with DOM object
		$(function () {
			$("#dom2jQuery").click(function () {
				var ele2 = document.getElementById("testDiv") // Get DOM object
				var $ele2 = $(ele2); // Convert DOM objects to jQuery objects
				alert($ele2.text()) // Get text through jQuery object
			})
		})

		// 3. Call jQuery method with jQuery object
		$(function () {
			$("#jQuery2jQuery").click(function () {
				var $ele3 = $("#testDiv "); / / get jQuery object
				alert($ele3.text()) // Get text through jQuery object

			})
		})

		// 4. Use jQuery object to call DOM method
		$(function () {
			$("#jQuery2dom").click(function () {
				var $ele4 = $("#testDiv"); //  Get jQuery object
				var ele4 = $ele4[0]; // Convert jQuery objects to DOM objects
				alert(ele4.innerText) // Get text from DOM object
			})
		})

	</script>


</head>
<body>
	<div id="testDiv">Squeeze into Shang Silicon Valley, destined to be excellent!</div>
	<br/>
	<button id="dom2dom">use DOM Object call DOM method</button>
	<button id="dom2jQuery">use DOM Object call jQuery method</button>
	<button id="jQuery2jQuery">use jQuery Object call jQuery method</button>
	<button id="jQuery2dom">use jQuery Object call DOM method</button>
</body>
</html>

Chapter 4 selector (key)

  • The best thing about jQuery is its powerful selector. Using its selector, you can basically find any node of the page quickly and easily

  • Selector classification of jquery

    • Basic selector
    • Level selector (or level selector)
    • Filter selector
      • basic
      • content
      • visibility
      • attribute
      • Child element
      • form
      • Form object properties

See documentation:

4.1 basic selector (key)

  • The basic selector is the simplest and most commonly used selector in jquery

  • It finds the matching DOM elements through tag name, id attribute and class attribute

1) id selector

  • Usage: $('#id')

  • Return value: match a tag according to the id attribute and encapsulate it into a jQuery object

  • give an example

    //HTML code:
    <div id="notMe"><p>id="notMe"</p></div>
    <div id="myDiv">id="myDiv"</div>
    
    //jQuery Code:
    $("#myDiv");
    
    //result:
    [ <div id="myDiv">id="myDiv"</div> ]
    

2) Label selector

  • Usage: $('tagName ')

  • Return value: encapsulates one or more tags that match the tag name into a jQuery object

  • give an example

    //HTML code:
    <div>DIV1</div>
    <div>DIV2</div>
    <span>SPAN</span>
    
    //jQuery Code:
    $("div");
    
    //result:
    [ <div>DIV1</div>, <div>DIV2</div> ]
    
    

3) class selector

  • Usage: $('. class')

  • Return value: match one or more tags according to the class attribute value and encapsulate them into a jQuery object

  • give an example:

    //HTML code:
    <div class="notMe">div class="notMe"</div>
    <div class="myClass">div class="myClass"</div>
    <span class="myClass">span class="myClass"</span>
    
    //jQuery Code:
    $(".myClass");
    
    //result:
    [ <div class="myClass">div class="myClass"</div>, <span class="myClass">span class="myClass"</span> ]
    

4) * selector

  • Usage: $("*")

  • Return value: matches all tags and encapsulates them into jQuery objects

  • give an example

    //HTML code:
    <div>DIV</div>
    <span>SPAN</span>
    <p>P</p>
    
    //jQuery Code:
    $("*")
    
    //result:
    [ <div>DIV</div>, <span>SPAN</span>, <p>P</p> ]
    

5) selector1,selector2,... (merge selector)

  • Usage: $("div,span,.myClass")

  • Return value: all tags matching the selector are encapsulated into jQuery objects

  • give an example:

    //HTML code:
    <div>div</div>
    <p class="myClass">p class="myClass"</p>
    <span>span</span>
    <p class="notMyClass">p class="notMyClass"</p>
    
    //jQuery Code:
    $("div,span,p.myClass") 
    //p.myClass: indicates that the tag name to be searched must be a p tag, and the class attribute must be myclass
    
    
    //Results: the order of the result data is inconsistent with the order of the elements to be queried, and is consistent with the order of the element declaration in HTML.
    [ <div>div</div>, <p class="myClass">p class="myClass"</p>, <span>span</span> ]
    

4.2 level selector (key)

  • If you want to get a specific element through the hierarchical relationship between DOM elements. For example, descendant elements, child elements, sibling elements, etc. You need to use the level selector (or level selector).

1) ancestor descendant

  • Usage: $("form input")
  • Description: match all descendant elements under a given ancestor element (including child elements of child elements,...)
    // html code
    <form>
      <label>Name:</label>
      <input name="name" />
      <fieldset>
          <label>Newsletter:</label>
          <input name="newsletter" />
     </fieldset>
    </form>
    <input name="none" />
    
    // jQuery code
    $("form input")
    
    // result
    [ <input name="name" />, <input name="newsletter" /> ]
    
    

2) parent > child

  • Usage: $("Form > input")
  • Description: matches all child elements under the specified parent element.
    • Note: distinguish the descendant element from the child element
      // html code
      <form>
        <label>Name:</label>
        <input name="name" />
        <fieldset>
            <label>Newsletter:</label>
            <input name="newsletter" />
       </fieldset>
      </form>
      <input name="none" />
      
      // jQuery code
      $("form > input")
      
      // result
      [ <input name="name" /> ]
      
      

3) prev + next

  • Usage: $("label + input")

  • Description: match all input elements following label

    • Note: look in the parent element instead of the child element.
      // html code
      <form>
        <label>Name:</label>
        <input name="name" />
        <fieldset>
            <label>Newsletter:</label>
            <input name="newsletter" />
       </fieldset>
      </form>
      <input name="none" />
      
      // jQuery code
      $("label + input")
      
      // result
      [ <input name="name" />, <input name="newsletter" /> ]
      
      

4) prev ~ siblings

  • Usage: $("form ~ input")

  • Note: all siblings after the prev element are matched, excluding this element, and siblings match elements of the same generation as prev, and subsequent elements are not matched.

    // html code
    <form>
      <label>Name:</label>
      <input name="name" />
      <fieldset>
          <label>Newsletter:</label>
          <input name="newsletter" />
     </fieldset>
    </form>
    <input name="none" />
    
    // jQuery code
    $("form ~ input")
    
    // result
    [ <input name="none" /> ]
    
    

4.3 filter selector: Basic

  • The filter selector is mainly used to filter out the required DOM elements through specific filter rules. The selector starts with ":

  • According to different filtering rules, filter selectors can be divided into basic filter, content filter, visibility filter, attribute filter, sub element filter, form filter and form object attribute filter selectors.

1) :first

  • Usage: $("tr:first");

  • Description: matches the first element found.

    // html code
    <ul>
        <li>list item 1</li>
        <li>list item 2</li>
        <li>list item 3</li>
        <li>list item 4</li>
        <li>list item 5</li>
    </ul>
    
    // jQuery code
    jQuery code:
    $('li:first');
    
    
    // result
    [ <li>list item 1</li> ]
    
    

2) :last

  • Usage: $("tr:last")

  • Description: match the last element found Corresponding to: first.

    // html code
    <ul>
        <li>list item 1</li>
        <li>list item 2</li>
        <li>list item 3</li>
        <li>list item 4</li>
        <li>list item 5</li>
    </ul>
    
    // jQuery code
    $('li:last')
    
    // result
    [ <li>list item 5</li> ]
    
    

3) :not(selector)

  • Usage: $("input:not(:checked)")

  • Description: removes all elements that match the given selector. It is similar to "not", which means that the input is not selected (when the type of input is "checkbox").

    // html code
    <input name="apple" />
    <input name="flower" checked="checked" />
    
    // jQuery code
    $("input:not(:checked)")
    
    // result
    [ <input name="apple" /> ]
    
    

4) :even

  • Usage: $("tr:even")

  • Description: match all elements with even index value and count from 0. js arrays are counted from 0.

    // html code
    <table>
      <tr><td>Header 1</td></tr>
      <tr><td>Value 1</td></tr>
      <tr><td>Value 2</td></tr>
    </table>
    
    // jQuery code
    $("tr:even")
    
    // result
    [ <tr><td>Header 1</td></tr>, <tr><td>Value 2</td></tr> ]
    
    

5) :odd

  • Usage: $("tr:odd")

  • Description: matches all elements with odd index values, corresponds to: even, and counts from 0.

    // html code
    <table>
      <tr><td>Header 1</td></tr>
      <tr><td>Value 1</td></tr>
      <tr><td>Value 2</td></tr>
    </table>
    
    // jQuery code
    $("tr:odd")
    
    // result
    [ <tr><td>Value 1</td></tr> ]
    
    

6) :eq(index)

  • Usage: $("tr:eq(0)")

  • Description: an element that matches a given index value. eq(0) is to get the first tr element. In parentheses are index values, not element permutations.

    // html code
    <table>
      <tr><td>Header 1</td></tr>
      <tr><td>Value 1</td></tr>
      <tr><td>Value 2</td></tr>
    </table>
    
    // jQuery code
    $("tr:eq(1)")
    
    // result
    [ <tr><td>Value 1</td></tr> ]
    

7) :gt(index)

  • Usage: $("tr:gt(0)")

  • Description: matches all elements greater than the given index value.

    // html code
    <table>
      <tr><td>Header 1</td></tr>
      <tr><td>Value 1</td></tr>
      <tr><td>Value 2</td></tr>
    </table>
    
    // jQuery code
    $("tr:gt(0)")
    
    // result
     result:
    [ <tr><td>Value 1</td></tr>, <tr><td>Value 2</td></tr> ]
    

8) :lt(index)

  • Usage: $("tr:lt(2)")
  • Description: matches all elements less than the given index value.
    // html code
    <table>
      <tr><td>Header 1</td></tr>
      <tr><td>Value 1</td></tr>
      <tr><td>Value 2</td></tr>
    </table>
    
    // jQuery code
    $("tr:lt(2)")
    
    // result
    [ <tr><td>Header 1</td></tr>, <tr><td>Value 1</td></tr> ]
    

9) : header,: animated,: focus omitted

: header: match header elements (h1~h6)
: animated: matches all elements that are performing animation effects

4.4 filter selector: content

  • The filtering rules of content filter selector are mainly reflected in its sub elements and text content

1) :contains(text)

  • Usage: $("div:contains('John ')")

  • Description: matches the element containing the given text. This selector is useful when we are not selecting dom tag elements. Its function is to find whether the text content enclosed by the label conforms to the specified content.

    // html code
    <div>John Resig</div>
    <div>George Martin</div>
    <div>Malcom John Sinclair</div>
    <div>J. Ohn</div>
    
    // jQuery code
    $("div:contains('John')")
    
    // result
    [ <div>John Resig</div>, <div>Malcom John Sinclair</div> ]
    

2) :has(selector)

  • Usage: $("div:has §") addClass(”test”)
  • Description: matches the element that contains the element that the selector matches. This explanation needs to be pondered over, but once you look at the example of use, it is completely clear: add class = "test" to all div tags containing p elements.
    // html code
    <div><p>Hello</p></div>
    <div>Hello again!</div>
    
    // jQuery code
    $("div:has(p)").addClass("test");
    
    // result
    [ <div class="test"><p>Hello</p></div> ]
    

3) :empty

  • Usage: $("td:empty")

  • Description: matches all empty elements that do not contain child elements or text

    // html code
    <table>
      <tr><td>Value 1</td><td></td></tr>
      <tr><td>Value 2</td><td></td></tr>
    </table>
    
    // jQuery code
    $("td:empty")
    
    // result
    [ <td></td>, <td></td> ]
    

4) :parent

  • Usage: $("td:parent")
  • Description: matches elements that contain child elements or text. Note: here is ": parent" is not " parent”! Feeling is the opposite of "empty".
    // html code
    <table>
      <tr><td>Value 1</td><td></td></tr>
      <tr><td>Value 2</td><td></td></tr>
    </table>
    
    // jQuery code
    $("td:parent")
    
    // result
    [ <td>Value 1</td>, <td>Value 2</td> ]
    

4.5 filter selector: visibility

  • Select the corresponding element according to the visible and invisible state of the element

1) :hidden

  • Usage: $("tr:hidden")

  • Note: match all invisible elements. If the type attribute of the input element is "hidden", it will also be matched. This means that both display:none and input type = "hidden" in css will be matched. Similarly, completely distinguish the colon from the dot in your mind And comma.

2) :visible

  • Usage: $("tr:visible")

  • Description: matches all visible elements.

4.6 filter selector: properties

  • The filtering rule of the attribute filter selector is to obtain the corresponding element through the attribute of the element.

1) [attribute]

  • Usage: $("div[id]")
  • Description: match the element containing the given attribute. In the example, all div tags with id attribute are selected.
    // html code
    <div>
      <p>Hello!</p>
    </div>
    <div id="test2"></div>
    
    // jQuery code
    $("div[id]")
    
    // result
    [ <div id="test2"></div> ]
    

2) [attribute=value]

  • Usage: $("input[name = 'newsletter']"). attr("checked", true)
  • Description: matching a given attribute is an element with a specific value. In the example, all the input elements whose name attribute is newsletter are selected.
    // html code
    <input type="checkbox" name="newsletter" value="Hot Fuzz" />
    <input type="checkbox" name="newsletter" value="Cold Fusion" />
    <input type="checkbox" name="accept" value="Evil Plans" />
    
    // jQuery code
    $("input[name='newsletter']").attr("checked", true);
    
    // result
    [ <input type="checkbox" name="newsletter" value="Hot Fuzz" checked="true" />, <input type="checkbox" name="newsletter" value="Cold Fusion" checked="true" /> ]
    

3) [attribute!=value]

  • Usage: $("input[name! =" newsletter "]"). attr("checked", true).
  • Description: matches all elements that do not contain the specified attribute or whose attribute is not equal to a specific value. This selector is equivalent to: not([attr=value]). To match elements with specific attributes but not equal to a specific value, use [attr]:not([attr=value]). What I saw before: not comes in handy.
    // html code
    <input type="checkbox" name="newsletter" value="Hot Fuzz" />
    <input type="checkbox" name="newsletter" value="Cold Fusion" />
    <input type="checkbox" name="accept" value="Evil Plans" />
    
    // jQuery code
    $("input[name!='newsletter']").attr("checked", true);
    
    // result
    [ <input type="checkbox" name="accept" value="Evil Plans" checked="true" /> ]
    

4) [attribute^=value]

  • Usage: $("input[name ^ = 'news']")
  • Note: matching a given attribute is an element starting with some values. We have seen these symbols similar to regular matching again. Now you can't forget it?!
    // html code
    <input name="newsletter" />
    <input name="milkman" />
    <input name="newsboy" />
    
    // jQuery code
    $("input[name^='news']")
    
    // result
    [ <input name="newsletter" />, <input name="newsboy" /> ]
    

5 ) [attribute$=value]

  • Usage: ( " i n p u t [ n a m e ("input[name ("input[name='letter']")
  • Description: matching a given attribute is an element that ends with some value.
    // html code
    <input name="newsletter" />
    <input name="milkman" />
    <input name="jobletter" />
    
    // jQuery code
    $("input[name$='letter']")
    
    // result
    [ <input name="newsletter" />, <input name="jobletter" /> ]
    

6) [attribute*=value]

  • Usage: $("input[name * =" man '] ")
  • Description: matching a given attribute is an element that contains some values.
    // html code
    <input name="man-news" />
    <input name="milkman" />
    <input name="letterman2" />
    <input name="newmilk" />
    
    // jQuery code
    $("input[name*='man']")
    
    // result
    [ <input name="man-news" />, <input name="milkman" />, <input name="letterman2" /> ]
    

7) [selector1] [selector2] [selectorN]

  • Usage: ( " i n p u t [ i d ] [ n a m e ("input[id] [name ("input[id][name='man']")
  • Note: composite attribute selector is used when multiple conditions need to be met at the same time.
    // html code
    <input id="man-news" name="man-news" />
    <input name="milkman" />
    <input id="letterman" name="new-letterman" />
    <input name="newmilk" />
    
    // jQuery code
    $("input[id][name$='man']")
    
    // result
    [ <input id="letterman" name="new-letterman" /> ]
    

4.7 filter selector: child elements

1) :nth-child(index/even/odd/equation)

  • Usage: $("UL Li: nth child (2)")

  • Description: matches the nth child or parity element under its parent element This selector is somewhat similar to eq() in basic filters, except that the former starts from 0 and the latter starts from 1.

// html code
<ul>
  <li>John</li>
  <li>Karl</li>
  <li>Brandon</li>
</ul>
<ul>
  <li>Glen</li>
  <li>Tane</li>
  <li>Ralph</li>
</ul>

// jQuery code
$("ul li:nth-child(2)")

// result
[ <li>Karl</li>,   <li>Tane</li> ]

2) :first-child

  • Usage: $("UL Li: first child")

  • Description: matches the first child element. * * ': First 'matches only one element, and this selector will match one child element for each parent element** We need to remember the difference here. Both callers are for the element to be manipulated.

    // html code
    <ul>
      <li>John</li>
      <li>Karl</li>
      <li>Brandon</li>
    </ul>
    <ul>
      <li>Glen</li>
      <li>Tane</li>
      <li>Ralph</li>
    </ul>
    
    // jQuery code
    $("ul li:first-child")
    
    // result
    [ <li>John</li>, <li>Glen</li> ]
    

3) :last-child

  • Usage: $("UL Li: last child")

  • Description: matches the last child element. ': Last 'matches only one element, and this selector will match a child element for each parent element.

    // html code
    <ul>
      <li>John</li>
      <li>Karl</li>
      <li>Brandon</li>
    </ul>
    <ul>
      <li>Glen</li>
      <li>Tane</li>
      <li>Ralph</li>
    </ul>
    
    // jQuery code
    $("ul li:last-child")
    
    // result
    [ <li>Brandon</li>, <li>Ralph</li> ]
    

4) : only-child

  • Usage: $("UL Li: only child")

  • Note: if an element is the only child element in the parent element, it will be matched. If the parent element contains other elements, it will not be matched. Only the of one child element will be matched!

// html code
<ul>
  <li>John</li>
  <li>Karl</li>
  <li>Brandon</li>
</ul>
<ul>
  <li>Glen</li>
</ul>

// jQuery code
$("ul li:only-child")

// result
[ <li>Glen</li> ]

4.8 filter selector: form

1) :input

  • Usage: $(": input")
  • Description: matches all text, textarea, select and button elements.
    // html code
    <form>
        <input type="button" value="Input Button"/>
        <input type="checkbox" />
    
        <input type="file" />
        <input type="hidden" />
        <input type="image" />
    
        <input type="password" />
        <input type="radio" />
        <input type="reset" />
    
        <input type="submit" />
        <input type="text" />
        <select><option>Option</option></select>
    
        <textarea></textarea>
        <button>Button</button>
    
    </form>
    
    // jQuery code
    $(":input")
    
    // result
    [ 
        <input type="button" value="Input Button"/>,
        <input type="checkbox" />,
    
        <input type="file" />,
        <input type="hidden" />,
        <input type="image" />,
    
        <input type="password" />,
        <input type="radio" />,
        <input type="reset" />,
    
        <input type="submit" />,
        <input type="text" />,
        <select><option>Option</option></select>,
    
        <textarea></textarea>,
        <button>Button</button>,
     ]
    

2) :text

  • Usage: $(": text")
  • Description: matches all single line text boxes.
    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":text")
    
    // result
    [ <input type="text" /> ]
    

3) :password

  • Usage: $(": password")
  • Description: matches all password boxes.
    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":password")
    
    // result
    [ <input type="password" /> ]
    

4) :radio

  • Usage: $(": radio")
  • Description: matches all radio buttons.
    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":radio")
    
    // result
    [ <input type="radio" /> ]
    

5) :checkbox

  • Usage: $(": checkbox")
  • Description: matches all check boxes.
    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":checkbox")
    
    // result
    [ <input type="checkbox" /> ]
    

6) :submit

  • Usage: $(": submit")
  • Description: matches all submit buttons.
    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":submit")
    
    // result
    [ <input type="submit" /> ]
    

7) :image

  • Usage: $(": image")
  • Description: matches all image fields.
    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":image")
    
    // result
    [ <input type="image" /> ]
    

8) :reset

  • Usage: $(": reset")

  • Description: matches all Reset buttons.

    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":reset")
    
    // result
    [ <input type="reset" /> ]
    

9) :button

  • Usage: $(": button")

  • Description: matches all buttons This includes the directly written element button.

    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":button")
    
    // result
    [ <input type="button" />,<button></button> ]
    

10) :file

  • Usage: $(": file")

  • Description: matches all file fields.

    // html code
    <form>
      <input type="text" />
      <input type="checkbox" />
      <input type="radio" />
      <input type="image" />
      <input type="file" />
      <input type="submit" />
      <input type="reset" />
      <input type="password" />
      <input type="button" />
      <select><option/></select>
      <textarea></textarea>
      <button></button>
    </form>
    
    // jQuery code
    $(":file")
    
    // result
    [ <input type="file" /> ]
    

11) :hidden

  • Usage: $("input:hidden")

  • Description: matches all invisible elements or elements of type hidden This selector is not limited to the form. In addition to matching hidden in input, those with hidden style will also be matched.

    // html code
    <table>
      <tr style="display:none"><td>Value 1</td></tr>
      <tr><td>Value 2</td></tr>
    </table>
    
    // jQuery code
    $("tr:hidden")
    
    // result
    [ <tr style="display:none"><td>Value 1</td></tr> ]
    
    // html code
    <form>
      <input type="text" name="email" />
      <input type="hidden" name="id" />
    </form>
    
    // jQuery code
    $("input:hidden")
    
    // result
     result:
    [ <input type="hidden" name="id" /> ]
    

4.9 filter selector: form object attribute

  • This selector mainly filters the selected form elements

1) :enabled

  • Usage: $("input:enabled")

  • Description: matches all available elements It means to find all input s without disabled = "disabled" Not disabled, of course enabled.

    // html code
    <form>
      <input name="email" disabled="disabled" />
      <input name="id" />
    </form>
    
    // jQuery code
    $("input:enabled")
    
    // result
    [ <input name="id" /> ]
    

2) :disabled

  • Usage: $("input:disabled")

  • Description: matches all unavailable elements It corresponds to the one above.

    // html code
    <form>
      <input name="email" disabled="disabled" />
      <input name="id" />
    </form>
    
    // jQuery code
    $("input:disabled")
    
    // result
    [ <input name="email" disabled="disabled" /> ]
    

3) :checked

  • Usage: $("input:checked")
  • Note: match all the selected elements (check boxes, radio boxes, etc., excluding the option in the drop-down list select).
    • Note: the official documentation does not include the option in select, but it is included in the test. It's just not recommended.
      // html code
      <form>
        <input type="checkbox" name="newsletter" checked="checked" value="Daily" />
        <input type="checkbox" name="newsletter" value="Weekly" />
        <input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
      </form>
      
      // jQuery code
      $("input:checked")
      
      // result
      [ <input type="checkbox" name="newsletter" checked="checked" value="Daily" />, <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> ]
      
      

4) :selected

  • Usage: $("select option:selected")

  • Description: matches all selected option elements.

    // html code
    <select>
      <option value="1">Flowers</option>
      <option value="2" selected="selected">Gardens</option>
      <option value="3">Trees</option>
    </select>
    
    // jQuery code
    $("select option:selected")
    
    // result
    [ <option value="2" selected="selected">Gardens</option> ]
    
    

Chapter 5 document processing (CRUD)

5.1 finding nodes

1) $(selector)

  • Query using jQuery selector

  • Get a jQuery object that contains all the matching dom node objects

    //jQuery Code:
    $("ul")
      .append("<li>" + $("ul").selector + "</li>")
      .append("<li>" + $("ul li").selector + "</li>")
      .append("<li>" + $("div#foo ul:not([class])").selector + "</li>");
    
    //result:
    ul
    ul li
    div#foo ul:not([class])
    

2) find(selector)

  • Query internal data of jQuery object

  • Find the matching descendant node in the Jquery object according to the selector

    //HTML code:
    <p><span>Hello</span>, how are you?</p>
    
    //jQuery Code:
    $("p").find("span")
    
    //result:
    [ <span>Hello</span> ]
    

3) eq(index)

  • Finds an element at a specified location in the collection based on the index value
  • The index starts from 0 and can also be - 1, - 2. Where - 1 is the last element
    //HTML code:
    <p> This is just a test.</p> <p> So is this</p>
    
    //jQuery Code:
    $("p").eq(1)
    // $("p":eq(1))
    //It can also be implemented directly using selectors. Why should it be extracted as a method? 
    //Because in development, jQuery objects are often set as variables, so you can use variables to call methods directly
    
    //result:
    [ <p> So is this</p> ]
    

4) filter(expr|obj|ele|fn)

  • Filter again from the caller based on the incoming selector string, etc
    //HTML code:
    <p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>
    
    //jQuery Code:
    $("p").filter(".selected")
    
    //result:
    [ <p class="selected">And Again</p> ]
    

5) children([expr])

  • Gets an element collection containing all child elements of each element in the matched element collection.
    //HTML code:
    <p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
    
    //jQuery Code:
    $("div").children()
    
    //result:
    [ <span>Hello Again</span> ]
    

6) parent([expr])

  • Gets a collection of elements that contains a unique parent element of multiple matching elements.
    //HTML code:
    <div><p>Hello</p><p>Hello</p></div>
    
    //jQuery Code:
    $("p").parent()
    
    //result:
    [ <div><p>Hello</p><p>Hello</p></div>]
    

7) parents([expr])

  • Gets a collection of elements containing the ancestor elements of all matching elements (excluding the root element). You can filter through an optional expression.
    //Find all ancestor elements for each span element.
    
    //HTML code:
    <html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
    
    //jQuery Code:
    $("span").parents()
    
    //Find all the ancestor elements of each span that are p elements.
    
    //jQuery Code:
    $("span").parents("p")
    

8) each(callback)

  • Traverse the data contained in the jQuery object: $(selector1) each(function(index, itemDom){ })
  • Traverse all nodes contained in the jQuery object, call the set callback function for each dom node object, and pass the subscript of the extracted node in the array and the node object into the function
    //Iterate over the two images and set their src properties. Note: this here refers to DOM object rather than jQuery object.
    
    //HTML code:
    <img/><img/>
    
    //jQuery Code:
    $("img").each(function(i){
       this.src = "test" + i + ".jpg";
     });
    
    //result:
    [ <img src="test0.jpg" />, <img src="test1.jpg" /> ]
    

5.2 obtaining length

1) Attribute: length

  • The number of elements in the jQuery object.
    //Calculate the number of all pictures in the document
    
    //HTML code:
    <img src="test1.jpg"/> <img src="test2.jpg"/>
    
    //jQuery Code:
    $("img").length;
    
    //result:
    2
    

2) Function: size()

  • The number of elements in the jQuery object. The function is the same as that of the length attribute.

5.3 internal insertion node

1) append(content)

  • Append content to the inner end of each matching element.
    //Append some HTML tags to all paragraphs.
    //HTML code:
    <p>I would like to say: </p>
    
    //jQuery Code:
    $("p").append("<b>Hello</b>");
    
    //result:
    [ <p>I would like to say: <b>Hello</b></p> 
    
    

2) appendTo(content)

  • Appends all matching elements to another specified set of elements
    // Append the p element to the div element.
    //HTML code:
    <p>I would like to say: </p>
    <div></div><div></div>
    
    //jQuery Code:
    $("p").appendTo("div");
    
    //result:
    <div><p>I would like to say: </p></div>
    <div><p>I would like to say: </p></div>
    
    
    //The new paragraph is appended to the div and a class is added
    //HTML code:
    <div></div><div></div>
    
    //jQuery Code:
     $("<p/>")
       .appendTo("div")
       .addClass("test")
       .end()
       .addClass("test2");
    //result:
    <div><p class="test test2"></p></div>
    <div><p class="test"></p></div>
    
    

3) prepend(content)

  • Insert content at the beginning of the interior of each matching element
    //Prefix all paragraphs with some HTML markup code.
    //HTML code:
    <p>I would like to say: </p>
    //jQuery Code:
    $("p").prepend("<b>Hello</b>");
    //result:
    [ <p><b>Hello</b>I would like to say: </p> ]
    
    //Prepends a DOM element into all paragraphs
    //HTML code:
    <p>I would like to say: </p>
    <p>I would like to say: </p>
    <b class="foo">Hello</b>
    <b class="foo">Good Bye</b>
    //jQuery Code:
    $("p").prepend( $(".foo")[0] );
    //result:
    <p><b class="foo">Hello</b>I would like to say: </p>
    <p><b class="foo">Hello</b>I would like to say: </p>
    <b class="foo">Good Bye</b>
    
    
    //Precede all paragraphs with a jQuery object (similar to an array of DOM elements).
    //HTML code:
    <p>I would like to say: </p><b>Hello</b>
    //jQuery Code:
    $("p").prepend( $("b") );
    //result:
    <p><b>Hello</b>I would like to say: </p>
    

4) prependTo(content)

  • Inserts each matching element at the beginning of the specified element
    //Append all paragraphs to the element with ID value foo.
    
    //HTML code:
    <p>I would like to say: </p><div id="foo"></div>
    
    //jQuery Code:
    $("p").prependTo("#foo");
    
    //result:
    <div id="foo"><p>I would like to say: </p></div>
    
    

5.4 external insertion node

1) after(content)

  • Insert content after each matching element
    //Insert some HTML markup code after all paragraphs.
    //HTML code:
    <p>I would like to say: </p>
    //jQuery Code:
    $("p").after("<b>Hello</b>");
    //result:
    <p>I would like to say: </p><b>Hello</b>
    
    
    
    //Insert a DOM element after all paragraphs.
    //HTML code:
    <b id="foo">Hello</b><p>I would like to say: </p>
    //jQuery Code:
    $("p").after( $("#foo")[0] );
    //result:
    <p>I would like to say: </p><b id="foo">Hello</b>
    
    
    //Insert a jQuery object (similar to an array of DOM elements) after all paragraphs.
    //HTML code:
    <b>Hello</b><p>I would like to say: </p>
    //jQuery Code:
    $("p").after( $("b") );
    //result:
    <p>I would like to say: </p><b>Hello</b>
    

2) before(content)

  • Insert content before each matching element
    //Insert some HTML markup code before all paragraphs.
    //HTML code:
    <p>I would like to say: </p>
    //jQuery Code:
    $("p").before("<b>Hello</b>");
    //result:
    [ <b>Hello</b><p>I would like to say: </p> ]
    
    
    //Insert an element before all paragraphs.
    //HTML code:
    <p>I would like to say: </p><b id="foo">Hello</b>
    //jQuery Code:
    $("p").before( $("#foo")[0] );
    //result:
    <b id="foo">Hello</b><p>I would like to say: </p>
    
    //Insert a jQuery object (similar to an array of DOM elements) before all paragraphs.
    //HTML code:
    <p>I would like to say: </p><b>Hello</b>
    //jQuery Code:
    $("p").before( $("b") );
    //result:
    <b>Hello</b><p>I would like to say: </p>
    

3) insertAfter(content)

  • Inserts all matching elements after another, specified set of elements
    //Insert all paragraphs after an element. And $("#foo") Same as after ("P")
    //HTML code:
    <p>I would like to say: </p><div id="foo">Hello</div>
    //jQuery Code:
    $("p").insertAfter("#foo");
    //result:
    <div id="foo">Hello</div><p>I would like to say: </p>
    

4) insertBefore(content)

  • Inserts all matching elements in front of another, specified set of elements
    //Insert all paragraphs before an element. And $("#foo") Before ("P") is the same.
    //HTML code:
    <div id="foo">Hello</div><p>I would like to say: </p>
    //jQuery Code:
    $("p").insertBefore("#foo");
    //result:
    <p>I would like to say: </p><div id="foo">Hello</div>
    

5.5 creating nodes

  • $(htmlString)

  • Dynamically created new element nodes will not be automatically added to the document, but need to be inserted into the document by other methods;

  • When creating a single element, pay attention to closed tags and use the standard XHTML format For example, to create a < p > element, you can use $("< P / >") or $("< p > < / P >"), but you cannot use $("< p >") or $("< / P >")

  • Creating a text node is to write the text content directly when creating an element node; The attribute node is also created when the element node is created

5.6 deleting nodes

1) empty()

  • Delete all child nodes (excluding itself) in the matching element collection.
    //Delete the sub elements (including text nodes) of all paragraphs
    //HTML code:
    <p>Hello, <span>Person</span> <a href="#">and person</a></p>
    //jQuery Code:
    $("p").empty();
    //result:
    <p></p>
    

2) remove()

  • Delete the matching element and its child elements (including itself)
    //Delete all paragraphs from DOM
    //HTML code:
    <p>Hello</p> how are <p>you?</p>
    //jQuery Code:
    $("p").remove();
    //result:
    how are
    
    //Delete the paragraph with the hello class from the DOM
    //HTML code:
    <p class="hello">Hello</p> how are <p>you?</p>
    //jQuery Code:
    $("p").remove(".hello");
    //result:
    how are <p>you?</p>
    

5.7 modifying nodes

1) replaceAll(selector)

  • Replace all elements matched by the selector with matching elements.
    //Replace all paragraph marks with bold marks
    //HTML code:
    <p>Hello</p><p>cruel</p><p>World</p>
    //jQuery Code:
    $("<b>Paragraph. </b>").replaceAll("p");
    //result:
    <b>Paragraph. </b><b>Paragraph. </b><b>Paragraph. </b>
    

2) replaceWith(content|fn)

  • Replace all matching elements with the specified HTML or DOM elements.
    //Replace all paragraph markers with bold ones.
    //HTML code:
    <p>Hello</p><p>cruel</p><p>World</p>
    //jQuery Code:
    $("p").replaceWith("<b>Paragraph. </b>");
    //result:
    <b>Paragraph. </b><b>Paragraph. </b><b>Paragraph. </b>
    
    
    //Replace the third paragraph with the first paragraph. You can find that it is moved to the target location to replace, rather than copying a copy to replace.
    //HTML code:
    <div class="container">
      <div class="inner first">Hello</div>
      <div class="inner second">And</div>
      <div class="inner third">Goodbye</div>
    </div>
    //jQuery Code:
    $('.third').replaceWith($('.first'));
    //result:
    <div class="container">
      <div class="inner second">And</div>
      <div class="inner first">Hello</div>
    </div>
    

Chapter 6 properties, HTML code, CSS

6.1 attribute operation

1) attr(name ,[value])

  • Attr (attribute name) returns the attribute value corresponding to "attribute name"

  • Attr (attribute name, attribute value) sets the attribute corresponding to "attribute name" to "attribute value"

    // Returns the src property value of all images in the document.
    $("img").attr("src");
    // Set the src property for all images.
    $("img").attr("src","test.jpg");
    

2) prop()

  • prop(): same as attr(). It's jquery1 After 6

3) removeAttr(name)

  • Delete the corresponding attribute according to the attribute name
    // Delete the src attribute of the image in the document
    
    //HTML code:
    <img src="test.jpg"/>
    
    //jQuery Code:
    $("img").removeAttr("src");
    
    //result:
    [ <img /> ]
    

6.2 HTML code / value

1)html([val])

  • Get the content of the element or set the content of the element
    //No parameter description: returns the contents of the p element.
    //jQuery Code:
    $('p').html();
    
    //Parameter val Description: sets the contents of all p elements
    //jQuery Code:
    $("p").html("Hello <b>world</b>!");
    
    //Callback function description: use the function to set the contents of all matching elements.
    //jQuery Code:
    $("p").html(function(n){
        return "this p Elemental index Yes:" + n;
        });
    

2)val([value])

  • val() read value attribute
  • val(value) sets the value attribute
  • val([option value 1, option value 2,..., option value n]) sets the selected value of radio box, multi box or drop-down list
    //No parameter description: gets the value in the text box
    //jQuery Code:
    $("input").val();
    
    //Parameter val Description: sets the value of the text box
    //jQuery Code:
    $("input").val("hello world!");
    
    //Callback function description: sets the value of the text box
    //jQuery Code:
    $('input:text.items').val(function() {
      return this.value + ' ' + this.className;
    });
    
    //Parameter array description: set the values of a select and a multi select select
    //HTML code:
    <select id="single">
      <option>Single</option>
      <option>Single2</option>
    </select>
    <select id="multiple" multiple="multiple">
      <option selected="selected">Multiple</option>
      <option>Multiple2</option>
      <option selected="selected">Multiple3</option>
    </select><br/>
    <input type="checkbox" value="check1"/> check1
    <input type="checkbox" value="check2"/> check2
    <input type="radio" value="radio1"/> radio1
    <input type="radio" value="radio2"/> radio2
    //jQuery Code:
    $("#single").val("Single2");
    $("#multiple").val(["Multiple2", "Multiple3"]);
    $("input").val(["check2", "radio1"]);
    

3)text()

  • text() gets the text content of the element node object

  • text(str) sets the text content of the element

    //No parameter description: returns the text content of the p element.
    //jQuery Code:
    $('p').text();
    
    //Parameter val Description: sets the text content of all p elements
    //jQuery Code:
    $("p").text("Hello world!");
    
    //Callback function description: use the function to set the text content of all matching elements.
    //jQuery Code:
    $("p").text(function(n){
        return "this p Elemental index Yes:" + n;
        });
    

6.3 CSS

1) addClass(className)

  • Add class attribute
    //Parameter class description:
    //Add the 'selected' class to the matching element
    //jQuery Code:
    $("p").addClass("selected");
    $("p").addClass("selected1 selected2");
    
    //Callback function description:
    //Add different class es to li
    //HTML code:
    <ul>
          <li>Hello</li>
          <li>Hello</li>
          <li>Hello</li>
    </ul>
    //jQuery Code:
    $('ul li:last').addClass(function() {
      return 'item-' + $(this).index();
    });
    

2) removeClass()

  • Remove class attribute
    //Parameter class description:
    //Remove the 'selected' class from the matching element
    //jQuery Code:
    $("p").removeClass("selected");
    
    //Parameter class description:
    //Delete all classes that match elements
    //jQuery Code:
    $("p").removeClass();
    
    //Callback function description:
    //Delete the duplicate class on the last element
    //jQuery Code:
    $('li:last').removeClass(function() {
        return $(this).prev().attr('class');
    });
    

3) css(name,[value])

  • View a style property, or set a style property
    //Parameter name Description:
    //Gets the value of the color style attribute of the first paragraph.
    //jQuery Code:
    $("p").css("color");
    
    //Parameter properties Description:
    //Set the font color of all paragraphs to red and the background to blue.
    //jQuery Code:
    $("p").css({ "color": "#ff0011", "background": "blue" });
    
    //Parameter name,value Description:
    //Set all paragraph fonts to red
    //jQuery Code:
    $("p").css("color","red");
    
    //Parameter name, callback function description:
    //Gradually increase the size of div
    //jQuery Code:
      $("div").click(function() {
        $(this).css({
          width: function(index, value) {
            return parseFloat(value) * 1.2;
          }, 
          height: function(index, value) {
            return parseFloat(value) * 1.2;
          }
        });
      });
    
    

Chapter 7 events

7.1 common events

1) ready(fn)

  • When the DOM is loaded and ready for query and operation, bind a function to be executed

  • It works with window Onload is different

Note: if window Onload declares more than one, and will not report an error, so as to finally give it to window The execution of the function assigned by onload shall prevail.
Description:

//The code that runs when the DOM is loaded can be written as follows:
//jQuery Code:
$(document).ready(function(){
  // Write your code here
});


//Use $(document) Ready (), and the internal jQuery code still uses $as the alias, regardless of the global $name.
//jQuery Code:
$(function($) {
  // You can continue to use $as an alias here
});

2) click([fn])

  • Trigger the click event of each matching element
    //Trigger the click event of all paragraphs in the page
    //jQuery Code:
    $("p").click();
    
    
    //Hide all paragraphs in the page after clicking.
    //jQuery Code:
    $("p").click( function () { $(this).hide(); });
    

3) blur([fn])

  • The blur event is triggered when the element loses focus, either by mouse action or by pressing tab to leave
    //Trigger the blur event for all paragraphs
    //jQuery Code:
    $("p").blur();
    
    
    //When any paragraph loses focus, a "Hello World!" pops up Handler bound in the blur event of each matching element.
    //jQuery Code:
    $("p").blur( function () { alert("Hello World!"); } );
    

4) change([fn])

  • The change event occurs when the value of an element changes.
  • This event applies only to text fields, as well as textarea and select elements. When used to select elements, the change event occurs when an option is selected. When used for text field or text area, this event occurs when the element loses focus
    //Trigger the change event of the selected element.
    //jQuery Code:
    $(selector).change();
    
    
    //Add input validation to all text boxes
    //jQuery Code:
    $("input[type='text']").change( function() {
      // You can write some verification code here
    });
    

5) live("event name", fn)

Event delegation: even if the subsequent added elements can be matched, they will be associated with related events.

6)mouseover(fn)

Mouse in event

7)mouseout(fn)

Mouse in event

7.2 binding and unbinding events

1) bind(type, fn)

  • Bind an event handler for a specific event for each matching element.
//When each paragraph is clicked, its text pops up.
//jQuery Code:
$("p").bind("click", function(){
  alert( $(this).text() );
});


//Bind multiple event types at the same time
//jQuery Code:
$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});


//Bind multiple event types / handlers at the same time
//jQuery Code:
$("button").bind({
  click:function(){$("p").slideToggle();},
  mouseover:function(){$("body").css("background-color","red");},  
  mouseout:function(){$("body").css("background-color","#FFFFFF");}  
});


//You can pass some additional data before event processing.
//jQuery Code:
function handler(event) {
  alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)


//Cancel the default behavior and prevent the event from bubbling by returning false.
//jQuery Code:
$("form").bind("submit", function() { return false; })


//Only the default behavior is cancelled by using the preventDefault() method.
//jQuery Code:
$("form").bind("submit", function(event){
  event.preventDefault();
});


//Only one event is prevented from bubbling by using the stopPropagation() method.
//jQuery Code:
$("form").bind("submit", function(event){
  event.stopPropagation();
});

2) unbind(type)

  • The reverse operation of bind() deletes the bound event from each matching element
//Unbind all events of all paragraphs
//jQuery Code:
$("p").unbind()


//Unbind the click event of a paragraph
//jQuery Code:
$("p").unbind( "click" )


//Delete the binding of a specific function and pass the function as the second parameter
//jQuery Code:
var foo = function () {
  // Code that handles an event
};
$("p").bind("click", foo); // ...  foo is triggered when a paragraph is clicked 
$("p").unbind("click", foo); // ...  It will never be triggered foo again

7.3 event switching

1) hover(over,out)

  • When the mouse moves over a matching element, the first function specified is triggered. When the mouse moves out of this element, the specified second function is triggered.

    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    
    	<script type="text/javascript" src="../../script/jquery-1.7.2.js"></script>
    	<script type="text/javascript">
    	
    		$(function(){
    			$("#h1").hover(function(){
    				alert("get into");
    			},function(){
    				alert("come out");
    			});
    		});
    	
    	</script>
    </head>
    <body>
    
    	<h1 id="h1" style="background-color: red">I'm the title</h1>
    
    </body>
    

2) Event bubbling

  • Description: the event will go up to the top like a bubble according to the DOM hierarchy. That is, the event triggering of the child element causes the event triggering of the parent element

  • Solution: return false in the event handler function to stop bubbling the event

    // HTML code
    <div id="content">
    	Outer layer div element
    	<span>Inner layer span element</span>
    	Outer layer div element
    </div>
    // jQuery code
    $(function(){
    	// Click events associated with div
    	$("#content").click(function () {
    		alert("div");
    	})
    
    	// Associated click events
    	$("span").click(function () {
    		alert("span");
    		// Cancel event bubbling. If you don't cancel, after the click event of playing span tag, you will continue to execute the click event of div tag
    		return false; 
    	})
    	
    })
    

Chapter 8 effect (optional)

8.1 basic

1) show()

  • Show hidden matching elements.
  • This is the non animated version of 'show (speed, [callback]). If the selected element is visible, this method will not change anything. Whether this element is hidden through the hide() method or set display:none; in CSS;, This method will work.
    //Show all paragraphs
    //HTML code:
    <p style="display: none">Hello</p>
    //jQuery Code:
    $("p").show()
    
    
    //Show hidden paragraphs with slow animation for 600 milliseconds.
    //HTML code:
    <p style="display: none">Hello</p>
    //jQuery Code:
    $("p").show("slow");
    
    
    //Show hidden paragraphs with a quick animation, which takes 200 milliseconds. And perform feedback later!
    //HTML code:
    <p style="display: none">Hello</p>
    //jQuery Code:
    $("p").show("fast",function(){
       $(this).text("Animation Done!");
     });
     
    
    //Show hidden paragraphs in nearly 4 seconds... And then perform a feedback...
    //HTML code:
    <p style="display: none">Hello</p>
    //jQuery Code:
    $("p").show(4000,function(){
       $(this).text("Animation Done...");
     });
    

2) hide()

  • Hide current label
//Hide all paragraphs
//jQuery Code:
$("p").hide()


//Slowly hide the paragraph in 600 milliseconds
//jQuery Code:
$("p").hide("slow");


//It takes 200 milliseconds to quickly hide the paragraph, and then a dialog box pops up.
//jQuery Code:
$("p").hide("fast",function(){
   alert("Animation Done.");
 });

3) toggle()

  • Switch the visibility of the current label. If the element is visible, switch to hidden; If the element is hidden, switch to visible.
//No parameter description:
//Toggle show / hide for table
//jQuery Code:
$('td').toggle();

//speed Description:
//It takes 600 milliseconds to slowly switch the paragraphs to the display state
//jQuery Code:
$("p").toggle("slow");

//speed,fn Description:
//It takes 200 milliseconds to quickly switch the paragraph to the display state, and then a dialog box pops up.
//jQuery Code:
$("p").toggle("fast",function(){
   alert("Animation Done.");
 });

//switch parameter description:
//If this parameter is true, the matching elements will be displayed; If false, the element is hidden
//jQuery Code:
$('#foo').toggle(showOrHide);
//amount to
if (showOrHide) {
  $('#foo').show();
} else {
  $('#foo').hide();
}   

8.2 sliding

1) slideDown()

  • This animation effect only adjusts the height of the element, so that the matching element can be displayed in a "sliding" way

2) slideUp()

  • This animation effect only adjusts the height of the element, so that the matching element can be hidden in a "sliding" way

3) slideToggle()

  • Toggles the visibility of all matching elements through height changes

8.3 fade in and fade out

1) fadeIn()

  • The fading effect of all matching elements is realized through the change of opacity

2) fadeOut()

  • Fade out all matching elements through the change of opacity

3) fadeToggle()

  • Switch the fade in and fade out effects of all matching elements through the change of opacity

Chapter 9 regular expressions

  • Why regular expressions
    • In software development, there are often strict requirements for data verification, such as: [user name can only be letters, numbers,. And the length is 6-15]. At this time, it is more convenient and safe to use regular expressions.
  • Regular expression overview: a set of rules for validating data.
  • use
    • Syntax:
      • var reg = / regular expression / official website
      • var reg = / ^ [rule]{m,n} $/ in actual development
    • Verify: reg Test (): returns a Boolean value.
var reg = /^[a-zA-z0-9_]{6,15}$/ // Match alphanumeric underscores with a length of 6-15
var res = reg.test("asdff1289578__")
alert(res)

Interview questions:

Question 1: what is the role of $in jQuery?

  • Answer: see 3.2

Question 2: what is the difference between jQuery objects and DOM objects? How to convert?

Question 3: what kinds of selectors does jQuery have?

Keywords: Javascript Front-end JQuery

Added by 44justin on Sun, 12 Dec 2021 15:14:49 +0200