JQuery quick table

1. Understand the jQuery

  • What is it?
    • A JS library: Write less, do more
    • Encapsulation simplifies DOM manipulation (CRUD)/Ajax
  • Why use it: Why?
    • Powerful selectors: Easy to find DOM elements quickly
    • Implicit traversal: Operating on more than one element at a time
    • Read/write: One function is used to read/write data
    • Chain call: can pass. Call jQuery object methods over and over again
    • The event processing
    • DOM manipulation (CUD)
    • Style operation
    • animation
    • Browser compatibility
  • How to use: How?
    • The introduction of the jQuery library
      • Local import and CDN remote import
<script src="Js/jquery - 1.10.1. Js" type="text/javascript"></script>
<script type="text/javascript">.</script>
Copy the code
JQuery functions: $/jQuery * jQuery objects: $XXX ($())Copy the code

2. JQuery 2 tools

JQuery function: $/jQuery

$(param); $(param); Onload = function(when the document is loaded) * param is a selector string that finds all matching DOM elements and returns the jQuery object containing all DOM elements. $(this) * param is a tag string: Create a tag DOM element object and wrap it as a jQuery objectCopy the code
1. Click the button: display the text of the button and display a new input box
  // 1). The argument is a function: this callback function is executed when the DOM is loaded
  $(function () {// bind the listener when the document has finished loading
  // 2). The argument is a selector string: find all matching labels and wrap them into jQuery objects
    $('#btn').click(function () {// Bind the click event listener
    // What is this? The DOM element where the event occurred (
    // alert(this.innerHTML)
    // 3). DOM object: encapsulate DOM object as jQuery object
      alert($(this).html())
      // 4). Parameter is HTML tag string (rarely used): create tag object and wrap it into jQuery object
      $('<input type="text" name="msg3"/><br/>').appendTo('div')})Copy the code

The jQuery object

$() returns a jQuery object * Basic behavior: * length/size(): number of DOM elements * [index] : Each (function(index, domEle){}): iterates over all dom elements * index(): retrieves the index of the current DOM element among all siblingsCopy the code
 // Requirement 2. Iterate over all element values in the output array
  var arr =[2.3.4.5]

    // $.each() : implicitly traverses the number group
    $.each(arr,function (index,item) {
    console.log(index,item)
  })
    3. Remove Spaces at both ends of "my atguigu"
    // $.trim() : remove Spaces on both ends
  var str = ' my confident'
    // console.log('---'+str.trim()+'---')
    console.log($.trim(str))
  })

Copy the code

3. Selector classification

* Strings with specific syntax rules (CSS selectors) * to find some DOM elements: $(selector)Copy the code

(1) Basic selector

  • #id
  • tagName/*
  • .class
  • Selector1 selector2, selector3: and set
  • Selector1selector2selector3: intersection

(2) Hierarchy selector

  • Look for the posterity, the brother element
  • Selector1 > selector2: child elements
  • Selector1 Selector2: Descendant element

(3) Filter selector

  • Filter out some of the original matching elements
  • :first
  • :last
  • :eq(index)
  • :lt
  • :gt
  • :odd
  • :even
  • :not(selector)
  • :hidden
  • :visible
  • 【 attrName 】
  • 【 attrName = value 】
<script src="Js/jquery - 1.10.1. Js" type="text/javascript"></script>
<script type="text/javascript">

  /* Need: 1. Select the first div. 2. Select the last element whose class is box. Select all div with class attribute not box 4. Select the second and third li elements 5. Select li with BBBBB 6. Select hidden Li 7. Select li with title 8. Select all li elements */ whose title is Hello
  $('div:first').css('background'.'red'The $()'.box:last').css('background'.'red'The $()'div:not(.box)').css('background'.'red'The $()'li:gt(0):lt(2)').css('background'.'red'The $()'li:lt(3):gt(0)').css('background'.'red'The $()'li:contains("BBBBB")').css('background'.'red')
  console.log($('li:hidden').length,$('li:hidden') [0$(])'li[title]').css('background'.'red'The $()'li[title="hello"]').css('background'.'red')

</script>
Copy the code

(4) Form selector

  • :input
  • :text
  • :checkbox
  • :radio
  • : checked: selected

tool

<script src="Js/jquery - 1.10.1. Js" type="text/javascript"></script>
<script type="text/javascript">
//1. $.each(): iterates over the data in a group or object
let arr = [1.2.3.5];
  $.each(arr,function (index,item) {
      console.log(index,item)
    })
  // 2. $.trim(): Removes whitespace from both sides of the string
  // 3. $.type(obj): get the type of the data
  console.log($.type($))//function
  // 4. $. IsArray (obj): check whether it is an array
  console.log($.isArray($))//false
  // 5. $.isfunction (obj): check whether it is a function
  console.log($.isFunction($))//true
  // 6. $.parsejson (json) : Parses json strings into JS objects/arrays
  var json = '{" name ":" Tony ", "age" : "14"}';
  console.log($.parseJSON(json))//json object === JS object
  json = '[{" name ":" Tom ", "age" : "12"}, {" name ":" lily ", "age" : "18"}]'
  console.log($.parseJSON(json))//json array === "JS object

Json.stringify (jsObj/jsArr) js object/array === "JSON string
</script>
Copy the code

02_ Multi-tab click toggle

   var $contents = $('#container>div')

   var currIndex = 0 // The subscript of the currently displayed content div
   // Add listener for 3 li
   $('#tab>li').click(function () {// implicit traversal
     // Hide the div of the currently displayed content
     $contents[currIndex].style.display = 'none'
     // Display the corresponding div
     // Get the index of the sibling of the current click li
     var index = $(this).index()
     // Find the corresponding content div and display it
     $contents[index].style.display = 'block'
   // Update the subscript
     currIndex = index
   })
Copy the code

4. Attributes/text

  • Manipulation of tag properties, tag body text

    * attr(name)/attr(name, value): Read/write ** Non-Boolean ** Tag attributes * prop(name)/prop(name, value): RemoveAttr (name)/removeProp(name): remove attribute * addClass(classValue): addClass * removeClass(classValue): Removes class * val()/val(value): reads and writes the value of the tag * HTML ()/HTML (htmlString): reads and writes the tag body textCopy the code

    Pseudo (class) arrays

// 1. Read the title attribute of the first div
  console.log($('div:first').attr('title'))
  // 2. Set name to all divs (value = atguigu)
  $('div').attr('name'.'july')
  // 3. Remove the title attribute from all divs
  $('div').removeAttr('title')
  // set class=' July 'for all divs
  $('div').attr('class'.'july')

  // add class=' ABC 'to all divs
  $('div').addClass('abc')

  // 6. Remove July's class from all divs
  $('div').removeAttr('july')

  // 7. Get the body text of the last li tag
  console.log($('li:last').html())
  // set the first li tag body to "

MMMMMMM

"
$('li:first').html('<h1>mmmmmmmmm</h1>') // 9. Get the value in the input box console.log($(':text').val()) // 10. Set the input field to atguigu $(':text').val('july') // 11. Click the 'Select All' button to select all var $checkboxs = $(':checkbox'The $()'button:first').click(function () { $checkboxs.prop('checked'.true)})// 12. Click the 'Select None' button to select none $('button:last').click(function () { $checkboxs.prop('checked'.false)})Copy the code

5. The CSS modules

(1) style style

* CSS (styleName, Value): Set ** one ** style * CSS ({multiple style pairs}): set ** multiple ** stylesCopy the code
// 1. Get the color of the first p tag
  console.log($('p:first').css('color'))
  // 2. Set the text color of all p labels to red
  $('p').css('color'.'red')
  // 3. Set the font color for the second p (#ff0011), background (blue), width (300px), height (30px).
  $('p:eq(1)').css({
    color:'#ff0011'.background:blue,
    width:300.height:20
  })
Copy the code

(2) Position coordinates

* offset(): reads/writes the current element coordinates (origin is the upper left corner of the page) * Position (): reads/writes the current element coordinates (origin is the upper left corner of the parent element) * scrollTop()/scrollLeft(): reads/writes the element/page scroll bar coordinatesCopy the code
1. Click btn1
  $('#btn1').click(function () {
  // Prints the position of div1 relative to the upper left corner of the page
    var offset = $('.div1').offset()
    console.log(offset.left,offset.top)
    // Prints the position of div2 relative to the upper left corner of the page
    offset = $('.div2').offset()
    console.log(offset.left,offset.top)
    // Prints the position of div1 relative to the upper-left corner of the parent element
    var position = $('.div1').position()
    console.log(position.left,position.top)
    // Prints the position of div2 relative to the upper-left corner of the parent element
    var position = $('.div2').position()
    console.log(position.left,position.top)
  })

  // 2. 点击 btn2
  // Set the position of div2 relative to the upper-left corner of the page
  $('#btn2').click(function () {$('.div2').offset({
     left:50.top:100})})Copy the code

 // 1. Get the coordinates of the div or page scroll bar
  $('#btn1').click(function () {
    console.log($('div').scrollTop())
    console.log($('html').scrollTop()+$('body').scrollTop())
  })
  // 2. Scroll the div or page's scroll bar to the specified position
  $('#btn2').click(function () {$('div').scrollTop(400The $()'html,body').scrollTop(300)})Copy the code
<! DOCTYPE html><html>

<head>
  <meta charset="UTF-8">
  <title>03_ Back to top</title>
  <style>
    #to_top {
      width: 30px;
      height: 40px;
      font: 14px/20px arial;
      text-align: center;
      background: #06c;
      position: fixed;
      cursor: pointer;
      color: #fff;
      left: 1250px;
      top: 500px;
    }
  </style>
</head>
<body style="height: 2000px;">
<div id="to_top">Return to the top</div>

<script type="text/javascript" src="Jquery - 1.10.1. Js"></script>
<script type="text/javascript">
  $('#to_top').click(function () {
    //way 1: instant to the top
    // $('html,body').scrollTop(0)

  // way 2: smooth to top
    / / total distance
    var $page = $('html,body')
    var distance =$('html').scrollTop() + $('body').scrollTop()
    / / total time
    var time = 50
    // Interval time
    var intervalTime = 50
    var itemDistance = distance/(time/intervalTime)

    // Use a loop timer
    var intervalId = setInterval(function () {
      distance -= intervalTime
      // Stop the timer when you reach the top
      if (distance <= 0){
        distance = 0/ / / correction
        clearInterval(intervalId)// Clear the timer
      }
      $page.scrollTop(distance)
    },intervalTime)

  })
</script>

</body>
</html>
Copy the code

(3) size

* width()/height(): width/height
* innerWidth()/innerHeight(): width + padding
* outerWidth()/outerHeight(): width + padding + border
Copy the code

6. Filter module

(1) filtering

Return * first() * last() * eq(index) * filter(selector): Make a request to the current element * not(selector): make a request to the current element, and inverse * has(selector): make a request to descendants of the elementCopy the code

(2) lookup

Return * children(selector): child element * find(selector): child element * preAll(selector): child element Siblings * siblings(selector): Siblings * parent(): parent elementCopy the code

7. Document Processing (CUD) module

(1) increased

* append()/appendTo(): insert back * preppend()/preppendTo(): insert front * Before (): insert front * after(): insert backCopy the code

(2) removed

* Remove (): remove yourself and your inner children * empty(): empty(you are still there)Copy the code

(3) the update

* replaceWith()
Copy the code

8. Event module

(1) Bind events

* eventName(function(){}) * on(function(){}) * click, mouseenter/mouseleave mouseover/mouseout focus/blur * hover(function(){}, function(){})Copy the code

(2) Untying events

* off('eventName')
Copy the code

(3) Event delegation

The event listener is bound to the parent element, but the event occurs on the child element. The event bubbles to the parent element. But the event callback function is called on the child element: Event.target * Benefit * New element without event listener * Reduced number of listener (n==>1) * encoding * delegate(selector, 'eventName', Function (event){}) // This is a child element * undelegate('eventName')Copy the code

(4) Event coordinates

* Event.offsetx: Origin is the upper left corner of the current element * Event. clientX: Origin is the upper left corner of the window * Event. pageX: Origin is the upper left corner of the pageCopy the code

(5) Event correlation

* Stop event bubbling: event.stopPropagation() * Prevent event default: event.preventDefault()Copy the code

Event propagation

·1 Capture phase — This phase will start from the Window object and traverse all the way down to the target object. If any object is found to be bound to a response event, the corresponding processing will be done.

•2 Target stage – When this stage has been traversed, the response function bound to the target object is executed.

• 3 Event bubble phase — This phase is the reverse of the capture phase in which the event is propagated upward from the event target until the window object ends, at which point the response function bound to the object is also executed.

Disable default event: event.preventDefault() Disable event bubblings: event.stopPropagation()

9 Animation Effects

  • Change the style of the element over time
  • slideDown()/slideUp()/slideToggle()
  • fadeOut()/fadeIn()/fadeToggle()
  • show()/hide()/toggle()
  • Animate ({end style}, time, fun)
  • stop()

10. Plugin mechanism

  • Methods to extend jQuery function objects
 $.extend({
      xxx: fuction () {} / / this is $
    })
    $.xxx()
Copy the code
  • Methods to extend jQuery objects
 $.fn.extend({
      xxx: function(){}  This is a jQuery object
    })
    $obj.xxx()
Copy the code