Hello, I'm hottie. I'll organize jQuery learning tutorials for you today.
catalogue
6, Get and set element content
7, Get and set element properties
1, Introduction to jQuery
Definition of jQuery
jQuery is an encapsulation of JavaScript. It is a free and open source JavaScript function library. jQuery greatly simplifies JavaScript programming.
Role of jQuery
JQuery has the same function as JavaScript, which is responsible for web page behavior operation and increasing the interaction effect between web pages and users, but jQuery simplifies JavaScript programming and jQuery makes it easier to realize the interaction effect.
Advantages of jQuery
- jQuery is compatible with mainstream browsers and increases the development efficiency of programmers.
- jQuery simplifies JavaScript programming and code writing.
Summary
- jQuery is a free, open source JavaScript library
- Like JavaScript, jQuery is responsible for the interaction between web pages and users.
- The advantage of jQuery is that it is compatible with mainstream browsers and easier to write code.
2, Usage of jQuery
Introduction of jQuery
<script src="js/jquery-1.12.4.min.js"></script>
jQuery entry function
We know that using js to obtain tag elements needs to be obtained after the page is loaded. We set a function for the onload event attribute to obtain tag elements, and jquery provides a ready function to solve this problem, so as to ensure that there is no problem in obtaining tag elements. Its speed is faster than that of the native window.onload.
Example code of entry function:
<script src="js/jquery-1.12.4.min.js"></script> <script> window.onload = function(){ var oDiv = document.getElementById('div01'); alert('Native is acquired div: ' + oDiv); }; $(document).ready(function(){ var $div = $('#div01'); alert('jquery Acquired div: ' + $div); }); </script> <div id="div01">This is a div</div>
Short example code of entry function:
<script src="js/jquery-1.12.4.min.js"></script> <script> window.onload = function(){ var oDiv = document.getElementById('div01'); alert('Native is acquired div: ' + oDiv); }; /* $(document).ready(function(){ var $div = $('#div01'); alert('jquery div obtained: '+ $div); }); */ // The above expression of ready can be abbreviated into the following form: $(function(){ var $div = $('#div01'); alert('jquery Acquired div: ' + $div); }); </script> <div id="div01">This is a div</div>
Summary
- Introducing jQuery
- Getting the tag element needs to be done in the entry function, which is faster than the native window.onload
-
There are two ways to write jQuery entry functions:
// Complete writing $(document).ready(function(){ ... }); // Simplified writing $(function(){ ... });
3, jQuery selector
Introduction to jQuery selector
jquery selector is to quickly select label elements and obtain labels. The selection rules are the same as css style.
The type of jQuery selector
- tag chooser
- Class selector
- id selector
- Level selector
- attribute selectors
Example code:
$('#myId ') / / select the tag with id myId $('.myClass') // Select the label whose class is myClass $('li') //Select all li Tags $('#ul1 li span ') / / select all the span tags under the li tag whose id is ul1 $('input[name=first]') // Select the input tag with the name attribute equal to first
explain:
You can use the length attribute to judge whether the label is selected successfully. If the length is greater than 0, the selection is successful, otherwise the selection fails.
$(function(){ result = $("div").length; alert(result); });
Summary
- The jQuery selector selects labels
- The label selector selects a label based on the label name
- The class selector selects the label based on the class name
- The id selector selects the tag based on the id
- The level selector selects labels according to the level relationship
- The attribute selector selects the label based on the attribute name
4, Selection set filtering
Introduction to selection set filtering
Selection set filtering is to filter the tags you need in the set of selected tags
Selection set filtering
- Has (selector name) method, indicating that the tag containing the specified selector is selected
- The EQ (index) method that selects the label of the specified index
Example code of has method:
<script> $(function(){ // Use of has method var $div = $("div").has("#mytext"); // Set style $div.css({"background":"red"}); }); </script> <div> This is the first div <input type="text" id="mytext"> </div> <div> This is the second div <input type="text"> <input type="button"> </div>
Example code of eq method:
<script> $(function(){ // Use of has method var $div = $("div").has("#mytext"); // Set style $div.css({"background":"red"}); // Use of eq method var $div = $("div").eq(1); // Set style $div.css({"background":"yellow"}); }); </script> <div> This is the first div <input type="text" id="mytext"> </div> <div> This is the second div <input type="text"> <input type="button"> </div>
Summary
- Selection set filtering can be done using has method and eq method
- jquery sets the style for the label and uses css method
5, Selection set transfer
Introduction to selection set transfer
Selection set transfer refers to the selected label, and then obtains the transferred label
Selection set transfer operation
- $('#box').prev(); Indicates that the selection id is the sibling element of the previous box element
- $('#box').prevAll(); Indicates that the selection id is all the sibling elements above the box element
- $('#box').next(); Indicates that the selection id is the next sibling element of the box element
- $('#box').nextAll(); Indicates that the selection id is all the sibling elements below the box element
- $('#box').parent(); Indicates that the selection id is the parent element of the box element
- $('#box').children(); Indicates that the selection id is all child elements of the box element
- $('#box').siblings(); Indicates that the selection id is another sibling element of the box element
- $('#box').find('.myClass'); Indicates that the selection id is the element whose class of box element is equal to MyClass
Sample code for selection set transfer:
<script> $(function(){ var $div = $('#div01'); $div.prev().css({'color':'red'}); $div.prevAll().css({'text-indent':50}); $div.next().css({'color':'blue'}); $div.nextAll().css({'text-indent':80}); $div.siblings().css({'text-decoration':'underline'}) $div.parent().css({'background':'gray'}); $div.children().css({'color':'red'}); $div.find('.sp02').css({'font-size':30}); }); </script> <div> <h2>This is the first h2 label</h2> <p>This is the first paragraph</p> <div id="div01">This is a<span>div</span><span class="sp02">the second span</span></div> <h2>This is the second h2 label</h2> <p>This is the second paragraph</p> </div>
Summary
- prev() means to get the previous sibling element
- Prevlall() means to get all the above sibling elements
- next() means to get the next sibling element
- nextAll() means to get all the following sibling elements
- parent() means to get the parent element
- children() means to get all the child elements
- siblings() means to get other sibling elements
- find("selector name") means to get the element of the specified selector
6, Get and set element content
Use of html methods
The html method in jquery can get and set the html content of the tag
Example code:
<script> $(function(){ var $div = $("#div1"); // Gets the html content of the tag var result = $div.html(); alert(result); // Set the html content of the tag, and the previous content will be cleared $div.html("<span style='color:red'>Hello</span>"); // Append html content $div.append("<span style='color:red'>Hello</span>"); }); </script> <div id="div1"> <p>hello</p> </div>
explain:
Append html content to the specified tag using the append method
Summary
- Get and set the content of the element. Use: html method
- Append html content to the specified element. Use the: append method
7, Get and set element properties
Use of prop method
Previously, css method can be used to set style attributes for labels, so prop method can be used to set other attributes of labels.
Example code:
<style> .a01{ color:red; } </style> <script> $(function(){ var $a = $("#link01"); var $input = $('#input01') // Get element properties var sId = $a.prop("id"); alert(sId); // Set element properties $a.prop({"href":"http://www.baidu.com","title ": 'this is the link to Baidu'," class":"a01 "}); // Get value attribute // var sValue = $input.prop("value"); // alert(sValue); // Get the value attribute using the shorthand method val() var sValue = $input.val(); alert(sValue); // Set value $input.val("222222"); }) </script> <a id="link01">This is a link</a> <input type="text" id="input01" value="111111">
explain: Getting and setting the value attribute can also be done through the val method.
Summary
- The operation of getting and setting element attributes can be completed through the prop method
- Getting and setting the value attribute of an element can be done through the val method, which is more simple and convenient
8, jQuery event
Common events
- Click
- The blur() element loses focus
- The focus() element gets the focus
- mouseover() mouse entry (also triggered when entering child elements)
- mouseout() mouse leaving (also triggered when leaving child elements)
- ready() DOM loading completed
Example code:
<script> $(function(){ var $li = $('.list li'); var $button = $('#button1') var $text = $("#text1"); var $div = $("#div1") // Mouse click $li.click(function(){ // this refers to the object of the current event, but it is a native js object // this.style.background = 'red'; // $(this) refers to the jquery object of the current event $(this).css({'background':'gold'}); // Get the index value of the jquery object through the index() method alert($(this).index()); }); // It is generally used with buttons $button.click(function(){ alert($text.val()); }); // Get focus $text.focus(function(){ $(this).css({'background':'red'}); }); // Lose focus $text.blur(function(){ $(this).css({'background':'white'}); }); // Mouse entry $div.mouseover(function(){ $(this).css({'background':'gold'}); }); // Mouse away $div.mouseout(function() { $(this).css({'background':'white'}); }); }); </script> <div id="div1"> <ul class="list"> <li>List text</li> <li>List text</li> <li>List text</li> </ul> <input type="text" id="text1"> <input type="button" id="button1" value="click"> </div>
explain:
- this refers to the object of the current event, but it is a native js object
- $(this) refers to the jquery object of the current event
Summary
jQuery common events:
- Click
- The blur() element loses focus
- The focus() element gets the focus
- mouseover() mouse entry (also triggered when entering child elements)
- mouseout() mouse leaving (also triggered when leaving child elements)
- ready() DOM loading completed
9, Event agent
Introduction to event agent
Event agent uses the principle of event bubbling (event bubbling means that the event will be passed to its parent level), adds the event to the parent level, and executes the operation of the corresponding child elements by judging the event source. Firstly, event agent can greatly reduce the number of event binding times and improve the performance; Secondly, the newly added child elements can also have the same operation.
Event bubble Code:
<script> $(function(){ var $div1 = $('#div1'); var $div2 = $('#div2'); $div1.click(function(){ alert($(this).html()); }); $div2.click(function(){ alert($(this).html()); }); }); </script> <div id="div1" style="width:200px; height:200px; background: red;"> <div id="div2" style="width:100px; height:100px;background: yellow;"> ha-ha </div> </div>
explain:
When the child element div is clicked, its click event will be passed to its parent element, and the click event of the parent element will also be triggered, which is event bubbling.
Use of event agent
Writing method of general binding event:
$(function(){ $ali = $('#list li'); $ali.click(function() { $(this).css({background:'red'}); }); }) <ul id="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul>
Writing of event agent
$(function(){ $list = $('#list'); // The parent element ul represents the click event of the child element li $list.delegate('li', 'click', function() { // $(this) indicates the child element object currently clicked $(this).css({background:'red'}); }); }) <ul id="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul>
Parameter description of delegate method:
delegate(childSelector,event,function)
- childSelector: selector for child elements
- Event: event name, for example: 'click'
- Function: the function executed when the event is triggered
Summary
- Event proxy is to use the parent element to proxy the events of child elements. The advantage is to reduce the binding times of events and improve performance.
- Use scenario when multiple identical child elements are bound to the same event, you can use the event proxy.
- The event proxy is done using the delegate method
10, JavaScript object
Introduction to JavaScript objects
All things in JavaScript are objects: strings, values, arrays, functions, etc. can be regarded as objects. In addition, JavaScript allows custom objects, which can have properties and methods.
JavaScript create object operation
There are two ways to create custom javascript objects:
- Instantiate an Object through the top-level Object type
- Create an object by object literal
Example code of Object class creating Object:
<script> var person = new Object(); // Add attribute: person.name = 'tom'; person.age = '25'; // Add method: person.sayName = function(){ alert(this.name); } // Call properties and methods: alert(person.age); person.sayName(); </script>
Example code for creating objects with object literals:
<script> var person2 = { name:'Rose', age: 18, sayName:function(){ alert('My name is' + this.name); } } // Call properties and methods: alert(person2.age); person2.sayName(); </script>
explain:
The operation of calling properties and methods is completed through point syntax. It is recommended to use literal method for object creation, because it is simpler.
Summary
There are two ways to create custom javascript objects:
- Object
- Literal
11, json
Introduction to json
json is the acronym of JavaScript Object Notation, which translates into javascript object representation. Here, json is a string similar to javascript objects. It is also a data format. At present, this data format is more popular and gradually replaces the traditional xml data format.
json format
json has two formats:
- Object format
- Array format
Object format:
For json data in object format, a pair of braces ({}) are used. Key value pairs in the form of key:value are placed in the braces, and multiple key value pairs are separated by commas.
json data in object format:
{ "name":"tom", "age":18 }
Format Description:
The (key) attribute name and string value in json need to be enclosed in double quotation marks. Using single quotation marks or not using quotation marks will lead to data reading errors.
Array format:
For json data in array format, a pair of brackets ([]) are used, and the data in brackets are separated by commas.
json data in array format:
["tom",18,"programmer"]
The json format actually developed is complex, for example:
{ "name":"jack", "age":29, "hobby":["reading","travel","photography"] "school":{ "name":"Merrimack College", "location":"North Andover, MA" } }
Convert json data into JavaScript objects
json is essentially a string. If you operate json data in js, you can convert the json string into a JavaScript object.
Example code:
var sJson = '{"name":"tom","age":18}'; var oPerson = JSON.parse(sJson); // Operation properties alert(oPerson.name); alert(oPerson.age);
Summary
- json is a javascript object representation. json is essentially a string.
- json has two formats: 1. Object format and 2. Array format
12, ajax
1. Introduction to Ajax
AJAX is short for Asynchronous JavaScript and XML. AJAX is a front-end and back-end technology. It allows javascript to send asynchronous http requests and communicate with the background for data acquisition. The biggest advantage of AJAX is to realize local refresh. Ajax can send http requests to update the page display data when the background data is obtained, Here, you only need to remember that if the current page wants to interact with the background server, you can use ajax.
Here's a reminder, Using ajax in html pages needs to run in the web server environment. Generally, you send ajax requests to your own web server.
2. Use of Ajax
jquery encapsulates it into a method $. ajax(), which we can use directly to execute ajax requests.
Example code:
<script> $.ajax({ // 1.url request address url:'http://t.weather.sojson.com/api/weather/city/101010100', // 2. The type request method is' GET 'by default, and' POST 'is also commonly used type:'GET', // 3.dataType sets the returned data format, commonly used as' json ' dataType:'JSON', // 4.data sets the data sent to the server. No parameters need to be set // 5.success sets the callback function after the request is successful success:function (response) { console.log(response); }, // 6.error set the callback function after the request fails error:function () { alert("request was aborted,Please try again later!"); }, // 7.async sets whether to be asynchronous. The default value is' true ', which means asynchronous. Generally, it is not necessary to write async:true }); </script>
Parameter description of ajax method:
- url request address
- The type request method is' GET 'by default, and' POST 'is commonly used
- dataType sets the format of the returned data. The commonly used format is' json '
- Data sets the data sent to the server. No parameters need to be set
- success sets the callback function after the request succeeds
- error sets the callback function after the request fails
- async sets whether it is asynchronous. The default value is' true ', which means asynchronous. Generally, there is no need to write
- Synchronous and asynchronous description
- Synchronization is that one ajax request is completed before another can be requested. You need to wait for the previous ajax request to complete, like thread synchronization.
- Asynchrony refers to multiple ajax requests at the same time without waiting for other ajax requests to complete. For example, threads are asynchronous.
Short for ajax:
$. ajax can be abbreviated as $. get or $. post according to the request mode
Sample code for ajax shorthand:
<script> $(function(){ /* 1. url Request address 2. data Set the data sent to the server. No parameters need to be set 3. success Set the callback function after the request is successful 4. dataType Set the returned data format. The commonly used format is' json '. The default data format is intelligent judgment */ $.get("http://t.weather.sojson.com/api/weather/city/101010100", function(dat,status){ console.log(dat); console.log(status); alert(dat); }).error(function(){ alert("Network exception"); }); /* 1. url Request address 2. data Set the data sent to the server. No parameters need to be set 3. success Set the callback function after the request is successful 4. dataType Set the returned data format. The commonly used format is' json '. The default data format is intelligent judgment */ $.post("test.php", {"func": "getNameAndTime"}, function(data){ alert(data.name); console.log(data.time); }, "json").error(function(){ alert("Network exception"); }); }); </script>
Parameter description of $. get and $. post methods:
$.get(url,data,success(data, status, xhr),dataType).error(func)
$.post(url,data,success(data, status, xhr),dataType).error(func)
- url request address
- Data sets the data sent to the server. No parameters need to be set
- success sets the callback function after the request succeeds
- Data the result data of the request
- Status the requested status information, such as "success"
- xhr sending http request XMLHttpRequest object at the bottom layer
- dataType sets the format of the returned data
- "xml"
- "html"
- "text"
- "json"
- Error indicates error exception handling
- func error exception callback function
3. Summary
- ajax is a technology that sends http request to get data from background server
- ajax can be abbreviated using $. get and $. post methods
Industry data: add to get PPT template, resume template, industry classic book PDF.
Interview question bank: the classic and hot real interview questions of large factories over the years are continuously updated and added.
Learning materials: including Python, crawler, data analysis, algorithm and other learning videos and documents, which can be added and obtained
Communication plus group: the boss points out the maze. Your problems are often encountered by others. Technical assistance and communication.