Write Less,Do More.
I met the jQuery
What?
An excellent JS function library that encapsulates DOM and BOM/Ajax
Application is very wide, medium and large WEB project development preferred
Why?
- HTML element picker (selector), jQuery extension selector to find tags
- HTML element manipulation
- CSS operation
- HTML event handling, user interaction
- JS animation Effect
- Chain call, a().b().c()
- Read/write synchrony: use one method to read or write an element
- Browser compatibility
- Easy extension plug-in
- Ajax encapsulation
- .
How?
-
Import jQuery library (JS file)
-
Using jQuery
- Using jQuery core functions ($/jQuery)
- JQuery core object: the object returned by executing $(“#btn2”
3. Two ways to introduce jQuery library
- Server local library, SRC absolute path
- CDN remote repository
JQuery’s two powerful tools
- JQuery core functions: directly available
- **$/jQuery** *
- After importing the jQuery library, use $directly
- When the function is used: $(XXXX)
- When the object uses: $.xxx()
- JQuery Core Object
- Get jQuery object: the object returned by executing the jQuery function
- Use jQuery object: $obj.xxx()
JQuery core functions
It can be used as a function (with ()) or as an object (calling a method)
-
Called as a function: $(XXX)
-
The parameter is a function. When the DOM is loaded, this callback function is executed
-
The argument is a selector string: find all matching labels and encapsulate them as jQuery objects
-
Parameter is DOM object: encapsulate DOM object as jQuery object and operate on it
-
Arguments are HTML tag strings (less) : create tag objects and wrap them into jQuery objects
// Function call arguments are functions $(function(){ // Selector string $("#btn1").click(function(){ // Bind event listeners alert($(this).html())//DOM object is converted to jQuery object and its methods are called $("<input type="text" name="msg3">").appendTo("div") // Insert input into the div tag})})Copy the code
-
-
To use as an object: $.xxx()
-
$.each(): implicitly traverses an object/array
var arr = [1.2.5] $.each(arr,function(index,item){ alert(index,item) }) Copy the code
-
$.trim(): Remove Spaces on both ends
var str = " aaa " $.trim(str) Copy the code
-
Use the jQuery core functions
The selector
Note: The selector itself is just a string with a specific syntax rule and has no real use. The basic syntax rules use and extend the CSS selector syntax, and only work if you call $and pass in the selector string as an argument.
$(selector): An array (pseudo) of matching labels that is found throughout the document according to the selector rules, encapsulated as a jQuery object
Basic selector
-
#id
-
element
-
.class
-
-
Selector1, Selector2, selectorN
-
Selector1selector2selectorN (overlap) find contain some properties of elements
// select the element with id div1 $("#div1").css("background"."red")// Use multiple objects.css ({}) // Select all div elements $("div").css("background"."red") // Select all elements whose class attribute is box $(".box").css("background"."red") // Select all div and SPAN elements $("div,span").css("background"."red") // Select all div elements whose class attribute is box $("div.class").css("background"."red") // All elements include body $("*").css("background"."red") Copy the code
Hierarchy selector
Selectors for finding child, descendant, and sibling elements
-
ancestor descendant
-
parent > child
-
prev + next
-
Prev ~ siblings (matches all siblings after the prev element)
// Select all span layers under ul $("ul span").css("background"."red") // Select all subelements span under ul $("ul>span").css("background"."red")// Child elements are all spans in the first layer of ul, not in the multiple layers // select the next li whose clas is box $(".box + li").css("background"."red") // Select all sibling elements after the element whose ul attribute is box $("ul .box~*").css("background"."red") Copy the code
Filter selector
Further filter selectors in the elements of the original selector matcher, multiple filter selectors executed in sequence!
-
basic
-
content
-
visibility
-
attribute
// select the first div $("div:first").css("background"."red")// select all divs and filter out the first one // Select the element whose last class is box $(".box:last").css("background"."red") // Select all divs whose class is not box $("div:not(.box)").css("background"."red")// No class attribute will work // Find something $(".box:eq(index)").css("background"."red") // Select the second and third li $("li:gt(0):lt(2)").css("background"."red")// Sequentially filter a:b:c,gt() for elements greater than subscript, lt() for elements less than subscript //$("li:lt(3):gt(0)").css("background","red") // select li with the content XXX $("li:contains("xxx")").css("background"."red") // Select li to hide (dispaly: None) console.log($("li:hidden").length,$("li:hidden") [0])//visible // Select li with the title attribute name $("li[title]").css("background"."red") // Select all li whose title is Hello $("li:[title = "hello"]").css("background"."red")// Hello double quotes can be added or not Copy the code
Form selector
// Select an unavailable text entry box
$(":text:disabled").css("background"."red")
// Select the number of explicit hobbies
$(":checkbox:checked").length
// Explicitly select the name of the city
$(":submit").click(function(){
var city = $("select>option:selected").html()
console.log(city)
})
Copy the code
JQuery Core Object
The jQuery object contains a pseudo-array of DOM element objects (maybe only one element). This object has many useful properties and methods to make it easier for programmers to manipulate the DOM
[Note] jQuery object and DOM element object methods are different!
Properties/methods
-
Basic behavior
-
Size ()/length: number of DOM elements
-
[index] / get(index) : gets the corresponding DOM element based on the index
-
Each () : Iterates over all DOM elements contained, distinguished from $.each()
-
Index () : Gets the index in the sibling element
// Count the number of buttons var $btns = $("button")/ / false array console.log($btns.length,$btns.size())/ / 4 // Retrieve the second button $btns[1].innerHTML//$BTNS [1], which is the DOM element. We've already taken it out, so we can use innerHTML // Outputs all button text $btns.each(function(inex,domEle){ console.log (index, domEle innerHTML,this)// This corresponds to the DOM element equivalent to domEle // Console. log(this) }) // Print the number of buttons that a certain button is console.log($("#btn3").index())/ / 2 Copy the code
-
Pseudo (class) arrays
- Object
- Length attribute
- Numeric subscript property
- Specific methods without arrays: forEach(), push (), pop ()
// Define a pseudo-array
var fArr = {}
fArr.length = 0
fArr[0] = "a"
fArr.length = 1
fArr[1] = "b"
fArr.length = 2
for (var i = 0; i<fArr.length; i++){var obj = fArr[i]
console.log(i,obj)
}
console.log(fArr.forEach)//false
Copy the code
$_ tool method
- $.each() : Iterates over the data in a group or object
- $.trim() : Removes whitespace from both sides of the string
- $.type(obj) : Gets the type of the data
- $. IsArray (obj) : Checks whether it is an array
- $.isfunction (obj) : checks whether it is a function
- $.parsejson (json) : Parses json strings into JS objects/arrays
//$.each() iterates over the object
var obj = {
name:"a".setName:function(name){
this.name = name
}
}
$.each(obj,function(key,value){
console.log(key,value)
})
//$.type($) function
//$.isArray($("a")) false
//$.parseJSON(json)
var json = '{"name":"Tom","age":12}'/ / a json object
var josn1 = '['{"name":"Tom"."age":12}', '{"name":"jack"."age":12}'] '/ / the json array
//json object/array ===> JS object/array
$.parseJSON(json)
JSON.parse(jsonString)//json object/array ===> JS object/array
JSON.stringify(jsObject/jsArray)//js object/array ===> JSON object/array
Copy the code
JQuery object Properties
// Read the title attribute of the first div
$('div:first').attr('title')
// Set the name attribute for all divs
$('div').attr('name'.'a')
// Remove the title attribute from all divs
$('div').removeAttr('title')//removeProp()
// Set class='aaa' for all divs
$('div').attr('class'.'aaa')
// Add class=' BBB 'to all divs. BBB corresponds to the CSS class name, which can have styles
$('div').addClass('bbb')//attr means Settings are overwritten, and add-ons are cumulative
// Remove the aaa class of all divs
$('div').removeClass('class'.'aaa')
// Get the tag text of the last li
$('li:last').html()asv
// Set the first li tag body to "aaa
"
$('li:first').html('<h1>aaa</h1>')
// Get the value of the input field
$(':text').val()// Note the distinction with the DOM value method
// Set the input field to ABC
$(':text').val('abc')// Combine reading and writing
// Click the 'select all' button to select all
//attr(): operates on attributes whose values are not Booleans
//prop(): specialises in manipulating properties with Boolean values
var $checkboxs = $(':checkbox'The $()'button:first').click(function(){ //property
$checkboxs.prop('checked'.true)})// Click the 'Select None' button to select none
var $checkboxs = $(':checkbox'The $()'button:last').click(function(){
$checkboxs.prop('checked'.false)})Copy the code