current position:Home>JQuery learning

JQuery learning

2022-04-29 08:09:57Chen Chen is trying

First time to know jQuery

what

  • An excellent person js function library
  • Used jQuery More than 90%
  • Medium large scale WEB Preferred for project development
  • write less, do more

why

  • HTML Element selection ( Selectors )
  • HTML Element operation
  • CSS operation
  • HTML Event handling
  • JS Animation effect
  • call chaining ( The return value of each method is this)
  • ** Integration of reading and writing (** Reading is for the first , Writing is for all )
  • Browser compatibility
  • Implicit traversal
  • Easy extension
  • ajax encapsulation

how

  1. introduce jQuery library
  2. Working with files
  • jQuery Core function : $ or jQuery
  • jQuery The core object : perform $() Returned object
  • Distinguish between two js Library file
    • Development Edition
    • Production version
  • Distinguish between two kinds of introduction js The way of library files
  • Local water diversion
  • CDN Library Remote import
    • Reduce the pressure on your server
  • jQuery Different versions of
  • 1.X
    • Compatible with older versions IE
    • The file is bigger
  • 2.X
    • part API I won't support it IE8 Up to
    • Small files and efficient execution
  • 3.X
    • Completely no longer supports IE8 Up to
    • Provides some new API
    • The offer does not contain ajax/ Animation API Version of

jQuery Two sharp weapons

jQuery Core function

abbreviation : jQuery function ($ or jQuery)

jQuery The only thing exposed to the library is $ or jQuery

  • When a function uses $()
    • Parameter is a function : When dom After loading, execute this callback function
    • The parameter is selector string : Find the matching tag and encapsulate it into jQuery object
    • Parameter is dom object : take dom Object encapsulation into jQuery object
    • Parameter is html Tag string : Create a label object and encapsulate it into jQuery object
<div>
    <button id="btn"> test </button>
    <br/>
    <input type="text" name="msg1"/><br/>
    <input type="text" name="msg2"/><br/>
</div>

<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
    /*  demand 1.  Click button :  Show the text of the button ,  Display a new input box   demand 2.  Traverse all element values in the output array   demand 3.  Get rid of " my atguigu " Spaces at both ends  */
    /* demand 1.  Click button :  Show the text of the button ,  Display a new input box */
    //1.1).  Parameter is a function  :  When DOM After loading , Execute this callback function 
    $(function () {
     //  The listener after the binding document is loaded 
        // 1.2).  The parameter is selector string :  Find all matching tags ,  And encapsulate them into jQuery object 
        $('#btn').click(function () {
     //  Binding click event listening 
            // this What is it? ?  What happened dom Elements (<button>)
            // alert(this.innerHTML)
            // 1.3).  Parameter is DOM object :  take dom Object encapsulation into jQuery object 
            alert($(this).html())
            // 1.4).  Parameter is html Tag string  ( Use less ):  Create a label object and encapsulate it into jQuery object 
            $('<input type="text" name="msg3"/><br/>').appendTo('div')
        })
    })
</script>
  • When the object uses $.()
    • $.each【 Implicitly traverse the array 】
    • $.trim【 Remove the spaces at both ends 】
    /* demand 2.  Traverse all element values in the output array */
    var arr = [2, 4, 7]
    // 1). $.each() :  Implicitly traverse the array 
    $.each(arr, function (index, item) {
    
        console.log(index, item)
    })
    // 2). $.trim() :  Remove the spaces at both ends 
    var str = ' my atguigu '
    // console.log('---'+str.trim()+'---')
    console.log('---' + $.trim(str) + '---')

jQuery The core object

  • abbreviation : jQuery object
  • obtain jQuery object : perform jQuery Function returns the object

understand

  • jq The object contains any number of matches dom Pseudo array of element objects ( There may be only one element )
  • jq Object has many useful properties and methods to facilitate operation dom

Basic behavior

  • size()/length Return contained dom Number of element objects
  • [index]/get(index) adopt index To find page index individual dom object
  • each() Pass in a callback function to traverse dom object
// Read dom Element method 1
var $buttons = $('button');
$buttons.each(function(index, domele){
    
    console.log(domele.innerHTML);
});
// Read dom Element method 2
var $buttons = $('button');
$buttons.each(function(){
    
    console.log(this.innerHTML);    // In the callback function this Refers to... In the current traversal dom Elements 
});
  • index() Returns the current jq The subscript of the position of the object in the sibling element

Pseudo array

  • yes Object object
  • length attribute
  • Array subscript property
  • There are no special methods for arrays , Such as forEach(), push(), pop(), splice() etc.
  console.log($buttons instanceof Array) // false
  //  Customize a pseudo array 
  var weiArr = {
    }
  weiArr.length = 0
  weiArr[0] = 'atguigu'
  weiArr.length = 1
  weiArr[1] = 123
  weiArr.length = 2
  for (var i = 0; i < weiArr.length; i++) {
    
    var obj = weiArr[i]
    console.log(i, obj)
  }
  console.log(weiArr.forEach, $buttons.forEach) //undefined, undefined

Use jQuery Core function

Selectors

The selector itself is just a string with specific syntax rules , No real use

Its basic grammar rules use css The selector syntax of , And the base is extended

Only a call $(),, And pass the selector as a parameter to work

$(selector)

  • Namely css Format of selector
  • Return encapsulated jQuery object

Basic selector

  • #id : id Selectors
  • element : Element selector
  • .class : attribute ( class ) Selectors
  • * : Any label
  • selector1,selector2,selectorN : Take the union of multiple selectors ( Combination selector )
  • selector1selector2selectorN : Take the intersection of multiple selectors ( Intersection selector )
<div id="div1" class="box">div1(class="box")</div>
<div id="div2" class="box">div2(class="box")</div>
<div id="div3">div3</div>
<span class="box">span(class="box")</span>
<br>
<ul>
  <li>AAAAA</li>
  <li title="hello">BBBBB(title="hello")</li>
  <li class="box">CCCCC(class="box")</li>
  <li title="hello">DDDDDD(title="hello")</li>
</ul>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> /*  demand : 1.  choice id by div1 The elements of  2.  Choose all div Elements  3.  Select all class The attribute is box The elements of  4.  Choose all div and span Elements  5.  Select all class The attribute is box Of div Elements  */ //1.  choice id by div1 The elements of  // $('#div1').css('background', 'red') //2.  Choose all div Elements  // $('div').css('background', 'red') //3.  Select all class The attribute is box The elements of  //$('.box').css('background', 'red') //4.  Choose all div and span Elements  // $('div,span').css('background', 'red') //5.  Select all class The attribute is box Of div Elements  //$('div.box').css('background', 'red') //$('*').css('background', 'red') </script>

Hierarchy selector

Hierarchy selector : Find child elements , Progeny element , Selector for sibling elements

  1. ancestor descendant
    Match all descendant elements under a given ancestor element
  2. parent>child
    Match all child elements under a given parent element
  3. prev+next
    Match all immediately after prev Elemental next Elements
  4. prev~siblings
    matching prev Everything after the element siblings Elements
<ul>
  <li>AAAAA</li>
  <li class="box">CCCCC</li>
  <li title="hello"><span>BBBBB</span></li>
  <li title="hello"><span class="box">DDDD</span></li>
  <span>EEEEE</span>
</ul>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> /*  demand : 1.  Choose ul Let's go through all the span 2.  Choose ul All the sub elements below span 3.  Choose class by box Next li 4.  Choose ul Under the class by box All sibling elements after the element of  */ //1.  Choose ul Let's go through all the span // $('ul span').css('background', 'yellow') //2.  Choose ul All the sub elements below span // $('ul>span').css('background', 'yellow') //3.  Choose class by box Next li // $('.box+li').css('background', 'yellow') //4.  Choose ul Under the class by box All sibling elements after the element of  $('ul .box~*').css('background', 'yellow') </script>

Filter selector

A selector that further filters the elements matched by the original selector

<div id="div1" class="box">class by box Of div1</div>
<div id="div2" class="box">class by box Of div2</div>
<div id="div3">div3</div>
<span class="box">class by box Of span</span>
<br/>
<ul>
  <li>AAAAA</li>
  <li title="hello">BBBBB</li>
  <li class="box">CCCCC</li>
  <li title="hello">DDDDDD</li>
  <li title="two">BBBBB</li>
  <li style="display:none"> I was hiding </li>
</ul>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> /*  demand : 1.  Select first div 2.  Choose the last class by box The elements of  3.  Select all class Property is not box Of div 4.  Choose the second and third li Elements  5.  The selection is BBBBB Of li 6.  Select hidden li 7.  Choose to have title Attribute li Elements  8.  Select all properties title by hello Of li Elements  */ //1.  Select first div // $('div:first').css('background', 'red') //2.  Choose the last class by box The elements of  //$('.box:last').css('background', 'red') //3.  Select all class Property is not box Of div // $('div:not(.box)').css('background', 'red') // No, class Properties can also be  //4.  Choose the second and third li Elements  // $('li:gt(0):lt(2)').css('background', 'red') //  Multiple filter selectors are not executed at the same time ,  But in turn  //$('li:lt(3):gt(0)').css('background', 'red') //5.  The selection is BBBBB Of li // $('li:contains("BBBBB")').css('background', 'red') //6.  Select hidden li // console.log($('li:hidden').length, $('li:hidden')[0]) //7.  Choose to have title Attribute li Elements  // $('li[title]').css('background', 'red') //8.  Select all properties title by hello Of li Elements  $('li[title="hello"]').css('background', 'red') </script>

Form selector

<form>
   user name : <input type="text"/><br>
   The secret   code : <input type="password"/><br>
   Love   good :
  <input type="checkbox" checked="checked"/> Basketball 
  <input type="checkbox"/> football 
  <input type="checkbox" checked="checked"/> badminton  <br>
   sex   other :
  <input type="radio" name="sex" value='male'/> male 
  <input type="radio" name="sex" value='female'/> Woman <br>
   Post   box : <input type="text" name="email" disabled="disabled"/><br>
   home :
  <select>
    <option value="1"> Beijing </option>
    <option value="2" selected="selected"> tianjin </option>
    <option value="3"> hebei </option>
  </select><br>
  <input type="submit" value=" Submit "/>
</form>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> /*  demand : 1.  Select the text entry box that is not available  2.  Displays the selected hobby   The number of  3.  Displays the name of the selected city  */ //1.  Select the text entry box that is not available  // $(':text:disabled').css('background', 'red') //2.  Displays the selected hobby   The number of  console.log($(':checkbox:checked').length) //3.  Displays the name of the selected city  $(':submit').click(function () {
       var city = $('select>option:selected').html() //  Select the option Label body text  city = $('select').val() //  Select the option Of value Property value  alert(city) }) </script>

$ Tool method

  1. $.each(): Traverse the data in an array or object
  2. $.trim(): Remove the spaces on both sides of the string
  3. $.type(obj): Get the type of data
  4. $.isArray(obj): Determine if it's an array
  5. $.isFunction(obj): Determine if it's a function
  6. $.parseJSON(json) : analysis json String conversion to js object / Array
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> //1. $.each():  Traverse the data in an array or object  var obj = {
       name: 'Tom', setName: function (name) {
       this.name = name } } $.each(obj, function (key, value) {
       console.log(key, value) }) //2. $.trim():  Remove the spaces on both sides of the string  //3. $.type(obj):  Get the type of data  console.log($.type($)) // 'function' //4. $.isArray(obj):  Determine if it's an array  console.log($.isArray($('body')), $.isArray([])) // false true //5. $.isFunction(obj):  Determine if it's a function  console.log($.isFunction($)) // true //6. $.parseJSON(json) :  analysis json String conversion to js object / Array  var json = '{"name":"Tom", "age":12}' // json object : {} // json object ===>JS object  console.log($.parseJSON(json)) json = '[{"name":"Tom", "age":12}, {"name":"JACK", "age":13}]' // json Array : [] // json Array ===>JS Array  console.log($.parseJSON(json)) /* JSON.parse(jsonString) json character string --->js object / Array  JSON.stringify(jsObj/jsArr) js object / Array --->json character string  */ </script>

attribute

  1. Operate on any property
    • attr()
    • removeAttr()
    • prop()
  2. operation class attribute
    • addClass()
    • removeClass()
  3. operation HTML Code / Text / value
    • html()
    • val()
<div id="div1" class="box" title="one">class by box Of div1</div>
<div id="div2" class="box" title="two">class by box Of div2</div>
<div id="div3">div3</div>
<span class="box">class by box Of span</span>
<br/>
<ul>
  <li>AAAAA</li>
  <li title="hello" class="box2">BBBBB</li>
  <li class="box">CCCCC</li>
  <li title="hello">DDDDDD</li>
  <li title="two"><span>BBBBB</span></li>
</ul>

<input type="text" name="username" value="guiguClass"/>
<br>
<input type="checkbox">
<input type="checkbox">
<br>
<button> Choose </button>
<button> Unchecked </button>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> //1.  Read the first div Of title attribute  console.log($('div:first').attr('title')) // one //2.  To all div Set up name attribute (value by atguigu) $('div').attr('name', 'atguigu') //3.  Remove all div Of title attribute  $('div').removeAttr('title') //4.  To all div Set up class='guiguClass' $('div').attr('class', 'guiguClass') //5.  To all div add to class='abc' $('div').addClass('abc') //6.  Remove all div Of guiguClass Of class $('div').removeClass('guiguClass') //7.  Get the last li Label body text  console.log($('li:last').html()) //8.  Set the first li The label body of is "<h1>mmmmmmmmm</h1>" $('li:first').html('<h1>mmmmmmmmm</h1>') //9.  Get the... In the input box value value  console.log($(':text').val()) //  Read  //10.  Set the value of the input box to atguigu $(':text').val('atguigu') //  Set up   Integration of reading and writing  //11.  Click on ' Future generations ' Button to select all  // attr():  Operate on attributes with non Boolean values  // prop():  Specifically operate on properties with Boolean values  var $checkboxs = $(':checkbox') $('button:first').click(function () {
       $checkboxs.prop('checked', true) }) //12.  Click on ' Totally unselected ' The button is not selected at all  $('button:last').click(function () {
       $checkboxs.prop('checked', false) }) </script>

CSS modular

CSS

<p style="color: blue;"> Descendants of Shang Silicon Valley </p>
<p style="color: green;"> Descendants of the sun </p>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> //1.  Get the first one p Label color  console.log($('p:first').css('color')) //2.  Set all p The text color of the label is red $('p').css('color', 'red') //3.  Set the first 2 individual p Font color for (#ff0011), background (blue), wide (300px),  high (30px) $('p:eq(1)').css({
       color: '#ff0011', background: 'blue', width: 300, height: 30 }) </script>

Location

offset([obj])

  • Returns the offset relative to the upper left corner of the page without parameters
  • Add parameter setting offset , Must be set at the same time top and left

position()

  • The offset from the upper left corner of the parent element
  • Cannot set offset
  • The return value is left And right Object of property
<style type="text/css"> * {
      margin: 0px;} .div1 {
       position: absolute; width: 200px; height: 200px; top: 20px; left: 10px; background: blue; } .div2 {
       position: absolute; width: 100px; height: 100px; top: 50px; background: red; } .div3 {
       position: absolute; top: 250px; } </style>
<body style="height: 2000px;">
    <div class="div1">
        <div class="div2"> test offset</div>
    </div>
    <div class='div3'>
        <button id="btn1"> Read offset and position</button>
        <button id="btn2"> Set up offset</button>
    </div>
    <script src="js/jquery-1.10.1.js" type="text/javascript"></script>
    <script type="text/javascript"> $('#btn1').click(function () {
       //  Print  div1  Position relative to the upper left corner of the page  var offset = $('.div1').offset() console.log(offset.left, offset.top) // 10 20 //  Print  div2  Position relative to the upper left corner of the page  offset = $('.div2').offset() console.log(offset.left, offset.top) // 10 70 //  Print  div1  Position relative to the upper left corner of the parent element  var position = $('.div1').position() console.log(position.left, position.top) // 10 20 //  Print  div2  Position relative to the upper left corner of the parent element  position = $('.div2').position() console.log(position.left, position.top) // 0 50 }) $('#btn2').click(function () {
       $('.div2').offset({
       left: 50, top: 100 }) }) </script>
</body>

scrollTop([val])

  • Get the vertical scrolling pixels of the element without setting parameters
  • Set the parameter to set the vertical scrolling pixel of the element
  • stay chrome And Firefox , The scrolling pixels of the browser scroll bar are body On
  • stay IE in , The scrolling pixels of the browser scroll bar are html On
 $(document.body).scrollTop()+$(document.documentElement).scrollTop()
//  Read the page scroll bar Y coordinate ( compatible chrome and IE)
 $('body,html').scrollTop(60);
//  Scroll to the specified position ( compatible chrome and IE)

scrollLeft([val])

  • Similar to vertical scrolling

Size

1.  Content size 
  height(): height
  width(): width
2.  Internal dimensions 
  innerHeight(): height+padding
  innerWidth(): width+padding
3.  External dimensions 
  outerHeight(false/true): height+padding+border   If it is true,  add margin
  outerWidth(false/true): width+padding+border  If it is true,  add margin
<script> var $div = $('div') // 1.  Content size  console.log($div.width(), $div.height()) // 2.  Internal dimensions  console.log($div.innerWidth(), $div.innerHeight()) // 3.  External dimensions  console.log($div.outerWidth(), $div.outerHeight()) console.log($div.outerWidth(true), $div.outerHeight(true)) </script>

Screening

jQuery Object filtering

 stay jQuery Object to filter out some elements from the object array 
1. first()
2. last()
3. eq(index|-index)
4. filter(selector)
5. not(selector)
6. has(selector)
<ul>
    <li>AAAAA</li>
    <li title="hello" class="box2">BBBBB</li>
    <li class="box">CCCCC</li>
    <li title="hello">DDDDDD</li>
    <li title="two"><span>BBBBB</span></li>
</ul>
<li>eeeee</li>
<li>EEEEE</li>
<br>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> var $liItem = $('ul>li');  1. ul Next li Label first  $liItem.first().css('background','red'); // 2. ul Next li The last one on the label  $liItem.last().css('background','red'); // 3. ul Next li The second part of the label  $liItem.eq(1).css('background','red'); // 4. ul Next li In the label title The attribute is hello Of  $liItem.filter('[title=hello]').css('background','red'); // 5. ul Next li In the label title Property is not hello Of  $liItem.not('[title=hello]').css('background','red'); $liItem.filter('[title!=hello]').css('background','red'); // 5.1 ul Next li There are tags in the tag. title attribute , but title Property is not hello Of  $liItem.not('[title][title!=hello]').css('background','red'); $liItem.filter('[title!=hello]').filter('[title]').css('background','red'); // 6. ul Next li There are tags in the tag. span Sub tag's  $liItem.has('span').css('background', 'red'); </script>

jQuery Object search

 Find the child according to the selector in the set of matched elements / Parents / Brother tag 
1. children():  Not found in sub tag 
2. find() :  Find... In the descendant tag 
3. parent() :  Parent label 
4. prevAll() :  All the brother labels in front 
5. nextAll() :  All the brothers in the back 
6. siblings() :  All the brother labels before and after 
<div id="div1" class="box" title="one">class by box Of div1</div>
<div id="div2" class="box">class by box Of div2</div>
<div id="div3">div3</div>
<span class="box">class by box Of span</span>
<br/>
<div>
    <ul>
        <span>span Text 1</span>
        <li>AAAAA</li>
        <li title="hello" class="box2">BBBBB</li>
        <li class="box" id='cc'>CCCCC</li>
        <li title="hello">DDDDDD</li>
        <li title="two"><span>span Text 2</span></li>
        <span>span Text 3</span>
    </ul>
    <span>span Text 444</span><br>
    <li>eeeee</li>
    <li>EEEEE</li>
    <br>
</div>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript">
    var $ul = $('ul')
    //1. ul The number of tags 2 individual span Child tags 
    $ul.children('span:eq(1)').css('background', 'red')
    //2. ul The number of tags 2 individual span Posterity label 
    $ul.find('span:eq(1)').css('background', 'red')
    //3. ul The parent label of the label 
    $ul.parent().css('background', 'red')
    //4. id by cc Of li All in front of the label li label 
    var $li = $('#cc')
    $li.prevAll('li').css('background', 'red')
    //5. id by cc Of li All the brothers of the label li label 
    $li.siblings('li').css('background', 'red')
</script>

Document processing

1.  add to / Replacement elements 
  * append(content)
     Insert the specified content to the last inside all the currently matched elements 
  * prepend(content)
     Insert the specified content to the front of all elements that currently match 
  * before(content)
     Inserts the specified content in front of all current matching elements 
  * after(content)
     Insert the specified content into the replacement node after all current matching elements 
  * replaceWith(content)
     Replace all matching tags with the specified content and delete nodes 
2.  Remove elements 
  * empty()
     Delete the child elements of all matching elements 
  * remove()
     Delete all matching elements 

Internal insert

append(content)
 Insert the specified content to the last inside all the currently matched elements 
prepend(content)
 Insert the specified content to the front of all elements that currently match 
//1.  towards id by ul1 Of ul Let's add one span( Last )
var $ul1 = $('#ul1')
//$ul1.append('<span>append() Added span</span>')
$('<span>appendTo() Added span</span>').appendTo($ul1)
//2.  towards id by ul1 Of ul Let's add one span( First )
//$ul1.prepend('<span>prepend() Added span</span>')
$('<span>prependTo() Added span</span>').prependTo($ul1)

External insert

before(content)
 Inserts the specified content in front of all current matching elements 
after(content)
 Insert the specified content into the replacement node after all current matching elements 
$('ul').before(htmlString | Element | Array | jQuery)  // towards ul Insert the element before the 
(htmlString | Element | Array | jQuery).insertBefore($('ul'))  // Insert elements into ul Before the label 
$('ul').after(htmlString | Element | Array | jQuery)  // towards ul Insert element after 
(htmlString | Element | Array | jQuery).insertAfter($('ul'))  // Insert elements into ul After tag 
//3.  stay id by ul1 Of ul Under the li(title by hello) Add before span
$ul1.children('li[title=hello]').before('<span>before() Added span</span>')

//4.  stay id by ul1 Of ul Under the li(title by hello) Add span
$ul1.children('li[title=hello]').after('<span>after() Added span</span>')

Replace

replaceWith(content)
 Replace all matching tags with the specified content and delete nodes 
$('ul').replaceWith('<p>a</p>')  // use p Label replacement ul label 
$('ul').replaceAll(Selector | jQuery | Array | Element)  // Replace... With the matching element ul label 
//5.  Will be in id by ul2 Of ul Under the li(title by hello) Replace all with p
$('#ul2>li[title=hello]').replaceWith('<p>replaceAll() Replacement p</p>')

remove

empty()
 Delete the child elements of all matching elements 
remove()
 Delete all matching elements 
$('ul').empty()  // Empty ul Internal child nodes 
$('ul').remove('li')  // Empty ul Inside li label 
//6.  remove id by ul2 Of ul All under li
// $('#ul2').empty() // Delete all child nodes in the matched element collection .
$('#ul2>li').remove() //

event

1.  Event binding (2 Kind of )* eventName(function(){
    })
     The event name corresponding to the binding ,	 for example :$('#div').click(function(){
    });
  * on(eventName, funcion(){
    })
     Generic binding event listener ,  for example :$('#div').on('click', function(){
    })
  *  Advantages and disadvantages :
    eventName:  Coding is convenient ,  But only one monitor can be added ,  And some event monitoring does not support 
    on:  Coding is inconvenient ,  You can add multiple listeners ,  And more versatile 
2.  Event unbundling :
  * off(eventName)
3.  Coordinates of events 
  * event.clientX, event.clientY   Relative to the upper left corner of the viewport 
  * event.pageX, event.pageY   Relative to the upper left corner of the page 
  * event.offsetX, event.offsetY  Relative to the upper left corner of the event element 
4.  Event related processing 
  *  Stop bubbling  : event.stopPropagation()
  *  Prevent event default behavior  : event.preventDefault()

Page load

  • ready(fn)

Event handling

  • .event()
  • .on(event, [selector, ][data, ]fn)
  • .off([event,][selector, ][fn])

mouseover And mouseenter The difference between

  • mouseover Corresponding mouseout

    When there are child elements inside , Moving in a child element triggers the of the parent element mouseout event

  • mouseenter Corresponding mouseleave

    There is no difference between whether there are child elements inside

difference on(‘eventName’, fun) And eventName(fun)

on(‘eventName’, fun): Universal , But coding is troublesome

eventName(fun): The coding is simple , But some events have no corresponding method

Event delegation

introduce : The problem of binding event listening : The new element doesn't listen . You can use event delegation to solve

1.  Event delegation ( delegate / agent ):
  *  Add multiple child elements (li) Delegate event listening to parent elements (ul) Handle 
  *  The listening callback is added to the parent element 
  *  When operating on any child element (li) when ,  Events bubble to parent elements (ul)
  *  Parent elements do not handle events directly ,  But according to event.target Get the child element of the event (li),  Call the event callback function through this child element 
2.  Event delegated 2 Fang :
  *  The delegate :  The owner   li
  *  Entrusted party :  The mediation   ul
3.  Benefits of using event delegates 
  *  Add a new child element ,  Automatic event response processing 
  *  Reduce the number of event listeners : n==>1
4. jQuery Event delegation for API
  *  Set event delegation : $(parentSelector).delegate(childrenSelector, eventName, callback)
  *  Remove event delegate : $(parentSelector).undelegate(eventName)
<ul>
  <li>1111</li>
  <li>2222</li>
  <li>3333</li>
  <li>4444</li>
</ul>
<li>22222</li>
<br>
<button id="btn1"> Add new li</button>
<button id="btn2"> Delete ul Event delegate listener on </button>
<script src="js/jquery-1.10.1.js"></script>
<script> //  Set event delegation  $('ul').delegate('li', 'click', function () {
       // console.log(this) this.style.background = 'red' }) $('#btn1').click(function () {
       $('ul').append('<li> Newly added li....</li>') }) $('#btn2').click(function () {
       //  Remove event delegate  $('ul').undelegate('click') }) </script>
  • delegate() // Old method
  • on() // The new method

Event coordinates

  • event.offsetX // From the upper left corner of the current element
  • event.clientX // From the top left corner of the view
  • event.pageX // From the top left corner of the page

Event correlation

  • Stop bubbling

    stopPropagation()

  • Blocking default behavior
    preventDefault()

Built in animation

Fade in and out

 Fade in and out :  Constantly changing the transparency of elements to achieve 
1. fadeIn():  Animated display ; Fade in 
2. fadeOut():  Hide with animation ; Fade out 
3. fadeToggle():  Toggle display with animation / hide 
 $div1.fadeOut(1000, function () {
    
      alert(' The animation is finished !!!')
    })

slide

 Slide animation :  Constantly changing the height of elements to achieve 
1. slideDown():  Unfold with animation 
2. slideUp():  Shrink with animation 
3. slideToggle():  Toggle expansion with animation / shrinkage 

Show and hide

 Show hidden , No animation by default ,  Animation (opacity/height/width)
1. show(): ( No ) Animated display 
2. hide(): ( No ) Hidden with animation 
3. toggle(): ( No ) Toggle display with animation / hide 

Custom animation

jQuery Animation essence  :  It is realized by constantly changing the element style value within a specified time 
1. animate():  Custom animation effects 
2. stop():  Stop Animation 
 <style type="text/css"> * {
      margin: 0px;} .div1 {
       position: absolute; width: 100px; height: 100px; top: 50px; left: 300px; background: red; } </style>
<button id="btn1"> To enlarge gradually </button>
<button id="btn2"> Move right down </button>
<button id="btn3"> Move left and up </button>
<button id="btn4"> Stop Animation </button>
<div class="div1">
   If there is a strong wind , Life doesn't give up !
</div>
<script src="js/jquery-1.10.1.js" type="text/javascript"></script>
<script type="text/javascript"> var $div1 = $('.div1'); $('#btn1').click(function () {
       /*$div1.animate({ width:200, height:200, },1000)*/ $div1 .animate({
       width:200, },1000) .animate({
       height:200, },1000) }) $('#btn2').click(function () {
       $div1.animate({
       left:500, top:100, },1000) }) $('#btn3').click(function () {
       $div1.animate({
       left:'-=100', top:'-=20', },1000) }) $('#btn4').click(function () {
       $div1.stop() }) </script>

Multiple libraries coexist

 problem  :  If there is 2 Both libraries have $,  There is conflict 
 solve  : jQuery The library can release $ Right to use ,  Let another library work properly ,  here jQuery Libraries can only use jQuery 了 
API : jQuery.noConflict()
<script type="text/javascript" src="js/myLib.js"></script>
<script type="text/javascript" src="js/jquery-1.10.1.js"></script>
<script type="text/javascript"> //  Release $ Right to use  jQuery.noConflict() //  call myLib Medium $ $() //  Want to use jQuery The function of ,  Only use jQuery jQuery(function () {
       console.log(' Document loading completed ') }) console.log('+++++') </script>

onload And ready The difference between

 difference : window.onload And  $(document).ready()
  * window.onload
    *  The callback will not be started until the image including the page is loaded ( On the evening of )
    *  There can only be one listening callback 
  * $(document).ready()
    *  Equate to : $(function(){})
    *  Call back after the page is loaded ( Good morning! )
    *  There can be multiple listening callbacks 

Customize jq plug-in unit

Extension plug-in

Expand jQuery The tool object of the function

  • $.extend(obj)

Expand jQuery Object tool object

  • $.fn.extend(obj)
/*  Customize simple plug-ins :  demand : 1.  to  $  add to 4 It's a tool and a method : * min(a, b) :  Returns a smaller value  * max(c, d) :  Returns a larger value  * leftTrim() :  Remove the space to the left of the string  * rightTrim() :  Remove the space to the right of the string  2.  to jQuery object   add to 3 Two functional methods : * checkAll() :  Future generations  * unCheckAll() :  Totally unselected  * reverseCheck() :  All negative selection  */
(function () {
    
  //  Expand $ Methods 
  $.extend({
    
    min: function (a, b) {
    
      return a < b ? a : b
    },
    max: function (a, b) {
    
      return a > b ? a : b
    },
    leftTrim: function (str) {
    
      return str.replace(/^\s+/, '')
    },
    rightTrim: function (str) {
    
      return str.replace(/\s+$/, '')
    }
  })
  //  Expand jQuery Object method 
  $.fn.extend({
    
    checkAll: function () {
    
      this.prop('checked', true) // this yes jQuery object 
    },
    unCheckAll: function () {
    
      this.prop('checked', false)
    },
    reverseCheck: function () {
    
      // this yes jQuery object 
      this.each(function () {
    
        // this yes dom Elements 
        this.checked = !this.checked
      })
    }
  })
})()

jQuery-validation

Form validation

  • Refer to the examples in the source code
  • Add attributes to tags to make validation rules
  • Use $().validate(obj) To turn on validation

jQuery UI

large jQuery The plug-in contains various sub plug-ins

laydate

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290809497424.html

Random recommended