jQuery knowledge point arrangement

Design idea of JQuery

  1. Multiple filtering methods
  $("#box").css("backgroundColor", "red")
  $(".b1").css("color", "green")
  $("ul li").css("marginTop", "10px")
  $("li.box").css("color", "red")
  $("li").filter(".box").css("color", "red")


  $("li:first").css("color", "red")
  $("li:last").css("color", "red")
  $("li:even").css("color", "red")
  $("li:odd").css("color", "red")
  $("li:eq(2)").css("color", "red")
  $("li").eq(2).css("color", "red")
  1. Method functionalization
    // Native js writing
    window.onload = function() {}
    
    // jquery writing
    $(function() {
      alert("Amount to window.onload")
    });
    
    // Add event
    $("li").click(function() {
      alert("I was clicked")
    })
    $("li").mouseover(function() {
      this.style.backgroundColor = "blue"
    })
    $("li").mouseout(function() {
      this.style.backgroundColor = "inherit"
    })
  1. Chain operation
  $(function() {
      $("h1")
      .click(function() {
        alert("I was clicked")
      })
      .css("color", "red")
      .mouseover(function() {
        this.style.backgroundColor = "#ccc"
      })
      .mouseout(function() {
        this.style.backgroundColor = "inherit"
      })
    })
  1. Value assignment combination
    // Native JS innerHTML
    // JQ
    $(function() {
      // Value
      alert($("#div").html());
      // assignment
      $("h1").html("<h1>I'm the new assignment</h1>")

      // Value
      console.log($("input").val())
      // assignment
      $("input").val("New content")
    })

JQuery method

  filter()  filter
        $("li").filter(".selected").css("color", "red")
  not()     And filter Contrary
        $("li").not(".selected").css("color", "red")
  has()     Determine whether the child node meets the conditions (the parent element is filtered)
        $("ul").has(".selected").css("color", "red");
  prev()    Last sibling element
        $("h2").prev().css("color", "red")
  next()    Next sibling element
        $("h2").next().css("color", "blue")
  find()    Find child nodes
        $("ul").find("li").css("color", "red");
        //Equivalent to $("ul li").css("color", "red");
  index()   Get the subscript of the current node in the sibling node
        console.log($("li.selected").index())
  eq()      Get elements by subscript
        $("li:eq(2)").css("color", "red")
  attr()   Setting and modifying properties between lines
        console.log($("div").attr("id")); // Get attributes
       $("div").attr("title", "world");   // set a property
        $("div").attr({                   // Modify multiple attributes at once
          title: "world",
          yyy: "zzz"
        })
  addClass()      Add to class
  removeClass()   delete class
        $("div").addClass("box2 box3")
  
  // How to get width
  width()             Content box
  innerWidth()        Stuffing box
  outerWidth()        Border box
  outerWidth(true)    contain margin
      $("#div").outerWidth()


  offset()          Get the current element directly (excluding margin),Distance from viewport
                  $("#div2").offset().left
  position()        Get the current element directly (including margin),Distance from the last parent node with positioning
  offsetParent()    Look up the first parent node with location,
                  $("#div2").offsetParent().css("backgroundColor", "red")

  val()       Obtain/Set values for form elements
              console.log($("input").val())   // Get can only get the first
              $("input").val("hello")   // Assignment, will assign values to all the retrieved elements
  size()      Output, get the number of elements
              console.log($("input").size())
              console.log($("input").length())
  each()      loop
              $("input").each(function(item, index) {
                item.value = index; // js writing
                $(item).val(index)  // jq writing
              })

  ready()     $(function(){})  ==  $(document).ready(function(){})
              document After loading, it must be window Loading completed( window.onload) before

  html()      Amount to innerHTML()  contain html Code
  text()      Amount to innerText()  Pure text


  //Data serialization
  serialize()       Splicing the data in the form into a query string( querystring) name1=value1&name2=value2
                    search        ?name1=value1&name2=value2
                    querystring   name1=value1&name2=value2
  serializeArray()  Concatenate the data in the form into an array
                    
                    <input type="text" name="a" value="1">
                    <input type="text" name="b" value="2">
                    $("input").serialize() // a=1&b=2


Event


  on()
  off()
      // Add an event to an element
      $("#div1").on("click", function() {
        alert("Be clicked")
      })

      // Add the same function to multiple events
      var i = 0;
      $("#div1").on("click mouseover", function() {
        $(this).html(i++)
      })

      // Add different functions to different events
      $("#div1").on({
        click: () => {alert("Clicked")},
        mouseover: function() {$(this).css("backgroundColor", "red")},
        mouseout: function() {$(this).css("backgroundColor", "chocolate")},
      })

      //Event delegation
      $("ul").on("click", "li", function() {
        $(this).css("color", "red");
      })
      
      var i = 5;
      $("#btn").on("click", function() {
        $(`<li>${i++ * 1111}</li>`).appendTo($("ul"))
      })

      // Cancellation event
      $("#cancel").click(() => {
        $("#div1").off(); / / cancel all events and all functions
        $("#div1").off("click "); / / cancel all functions of an event
        $("#div1").off("click", show); / / cancel the specified function under an event
      })

  // Get height 
  scrollTop
        $(window).scrollTop()


  // 1. Prevent events from bubbling
  ev.stopPropagation()
          $("div").click(function(ev) {
            alert(this.id);
            ev.stopPropagation();
          })
  // 2. Block default behavior
  ev.preventDefault()
  // 3. Prevent both event bubbling and default behavior
  return false
          $("div").click(function(ev) {
            return false
          })

  // Get mouse click position
  // 
        $(document).click(function(ev) {
          console.log(ev.pageX + " , " + ev.pageY)  // With rolling distance
          console.log(ev.clientX + " , " + ev.clientY)  // Viewport distance
        }) 

  which
      //Mouse event: button
        1   Left key
        2   Roller
        3   Right click
      keydown:  keyCode Code
      keyPress: charCode Code

            $(document).mousedown(function(ev) {
              console.log(ev.which); 
            })

            $(window).keydown(function(ev) {
              console.log(ev.which);
            })


  ev.target     Trigger object itself after compatibility    // < button > button < / button >
  ev.type       Output event type          // click

  ev.data       Parameters passed in
                $("button").on("click", {name: "aaa", age: 18}, function() {
                  console.log(ev.data);;   // Parameters passed in
                  console.log(ev.data.name);  // aaa
                })

  trigger        Active trigger(It can trigger official events or events bound by itself)
                $("#play").on("next", function() {
                  alert("Next one")
                })
                $("button").click(function() {
                  $("#play").trigger("next")
                })


Special effect function

  hover(funcOver, funcOut)  

  hide()
  show()
    //Two parameters can be passed in, hide (animation duration in milliseconds, callback function)
    [Note] animation effect, from the upper left corner, folded and expanded

  slideDown()
  slideUp()
    [Note] animation effect, from top to bottom

  fadeIn()
  fadeOut()
  fadeTo(Animation duration, transparency, callback function)
    [Note] animation effect, fade in and out
        $(function() {
          $("#div1").hover(function() {
            $("#div1").fadeTo(500,1 , function() {$("#div1").html(" move in ")})
            $("#div2").fadeIn(500, function() {$("#div1").html(" move in ")})
          }, function() {
            $("#div1").fadeTo(500, 0.5, function() {$("#div1").html(" move in ")})
            $("#div2").fadeOut(500, function() {$("#div1").html(" move out ")})
          })
        })

Node operation

  Insertbefore() before()
  Insertafter() after()
  Appendto() append() child element end insert
  Prependto() prepend() child element start insert
  remove() removes the node and returns the deleted node itself, but does not retain previous events and behaviors
  detach() removes the node, returns the deleted node itself, and preserves the previous events and behaviors
                    $("span").insertAfter($("div"))
  
  selector
  Add() $("div"). Add ("span"). Add ("UL Li"). Css() is equivalent to $("div, span, ul li").css()
  Slice (start, end) gets the element node $("ul li").slice(1,4).css()

  //[note] all the methods mentioned above can pass parameters. The parameter represents selector $("div2").siblings("h2").css("color", "red")
  siblings() all siblings except the current node
  All siblings after nextAll()
  All sibling elements before prevlall()
  parentsUntil() parent node, to Until
  Brother element after nextUntil(), to Until
  Brother element before prevUntil(), to Until




  parent() starts from the parent node and gets the first matching parent node
  parents() gets the parent nodes and can pass in parameters as selectors
  closest() must pass in a parameter as a selector to get the first matching parent node from itself


  Packing
  wrap() wraps each satisfied element with $("span"). Wrap ("< p class ='box '> P >")
  wrapAll() overall outer package
  wrapInner() inner wrapper (fill)
  unwrap() removes the previous layer of packaging (if any, if none, do not delete). There are no parameters

  clone() only clones the node itself by default, and does not clone
  clone(true) not only clone itself, but also clone behavior
                      var node = $("#div1").clone(true);
                      node.appendTo($("#div2"));
  

Animation function

  Animate (style, time, motion mode, callback function)
    Motion form: slow fast slow swing (default)
             Uniform linear
             For more sports, jQuery UI framework needs to be introduced (basically eliminated at present)


        $("#div1").click(function() {
          $("#div1").animate({
            width: 300,
            opacity: 0.5
          }, 4000, "swing", function() {$("" div1 "). HTML (" move in ")})

          $("#div2").animate({
            width: 300, 
            opacity: 0.5
          }, 4000, "linear", function() {$("" div2 "). HTML (" move in ")})
        })

    Stop animation stop() / / stops the current animation of the element, but the later animation still executes
            stop(true) / / stop all animation of this element 
            stop(true, true) / / stop all animations of this element and complete the current animation directly
            finish() / / stop all animations of this element and complete all animations directly

        $(function() {
           $("#div1").click(function() {
             $("#div1").animate({width: 300}, 2000)
             $("#div1").animate({height: 300}, 2000)
           })
           $("#div2").click(function() {
             $("ාdiv1").stop() / / stops the element's current animation, but the subsequent animation still executes
             $("ාdiv1").stop(true) / / stop all animation of this element
             $("ාdiv1").stop(true, true) / / stop all animations of this element and complete the current animation directly
              $("ාdiv1").finish() / / stop all animation of this element and complete all animation directly
           })
         })
    
    Tip: before calling animate, call stop(true) to cancel the previously accumulated animation
        $("#div1").stop(true).animate({width: 300}, 2000)

  Delay animation after delay time
        $("#div1").animate({width: 300}, 2000).delay(1000).animate({height: 300}, 2000)


jQuery tool method

  $.type()      data type    $.type(arr)
  $.trim()      Remove leading and trailing spaces  $.trim(str)    str.trim() (es6 Official grammar)
  $.inArray()   Find the subscript of data  $.inArray(30, arr)   arr.indexOf(30) (es6 Official grammar)
  $.proxy()     Similar function bind
  $.makeArray() Convert pseudo array to array  $.makeArray(arr)      Array.from(arr)  (es6 Official grammar)

  .noConflict()     to $Aliasing, using noConflict() Method is jQuery The variable specifies a new name:
                    var jq=$.noConflict();
  

jQuery plug-in method

  Add function to JQ
  $. extend() extends the tool method $. xxx()
  $. fn.extend() extends JQ method $(). xxx()

                    $.extend({
                      aaa: function() {
                        alert("this is a tool approach")
                      }
                    })

                    $.fn.extend({
                      bbb: function() {
                        alert("this is a JQ method")
                      }
                    })

cookie method of jQuery

  $.cookie()

  Format of specific call
  Value of $. cookie(name) through name
  $. cookie(name, value) sets name and value
  $.cookie(name, value, {
    Optional
    Raw: true, value is not encoded, default is false
    Expires: in 7 days
  })
  $. cookie(name, null) delete cookie

                          $.cookie("ming", "pwssss", {
                              expires: 7,
                              raw: false
                          })

ajax method of jQuery

  $().load()
  $.get()
  $.post()

  // How to use $. ajax()
        $(function() {
          $("#btn1").click(function() {
            $.ajax({
              type: "get",
              url: "1.txt",
              data: {
              },
              success: function(data, statusText, xhr) {
                /*
                  statusText: success error
                  xhr: ajax object
                */
                console.log(data);
                console.log(statusText)
              },
              error: function(msg) {
                console.log(msg)
              }
            })
          })
        })

  // Cross domain approach
        // Add
        dataType: "jsonp"
  
  // $.load()
  // $. Load (path and selector, callback function (data, statusText, xhr))
  // If there is html label in the data, you can add selector after the path to filter the acquired data
        $("button").click(function() {
          $("div").load("2.txt h2", function(data, statusText, xhr){
            console.log(data);
            console.log(statusText);
            console.log(xhr.status);
          })
        })

  // $.get()
  // $.get (path, callback function (data, statusText, xhr))
        $.get("1.txt", function(data, statusText, xhr) {
          console.log(data)
        })


  // $.post()
  // $. Post (path, callback function (data, statusText, xhr))
      

Tags: Front-end JQuery

Posted on Mon, 23 Mar 2020 06:35:30 -0400 by thimble