Front-end study notes (5) JavaScript framework jquery

What is jquery

jQuery is a fast and concise JavaScript framework. It is another excellent JavaScript code library (or JavaScript framework) after Prototype. The purpose of jQuery design is "write Less, Do More", that is, advocating to write less code and do more. It encapsulates the functional codes commonly used in JavaScript, provides a simple JavaScript design mode, optimizes HTML document operation, event handling, animation design and Ajax interaction.
JavaScript framework: In essence, some js files encapsulate the native code of js .

How to use jquery

jquery version

There are currently three major versions of jquery

  1. Compatible with ie678, the most widely used, the official only does BUG maintenance, and the function is no longer added. Therefore, for general projects , the 1.x version is enough, the final version: 1.12.4 (May 20, 2016).

  2. Not compatible with ie678, few people use it, the official only does BUG maintenance, and the function is no longer added. If you don’t consider compatible low-version browsers, you can use 2.x, the final version: 2.2.4 (May 20, 2016)

  3. Not compatible with ie786, only supports the latest browser, unless special requirements, ** generally will not use version 3.x, many old jquery plug-ins do not support this version, ** currently this version is the official main update and maintenance version . The latest version: 3.2.1 (March 20, 2017).

The difference between jquery-xxx.js and jquery-xxx.min.js:

  1. jquery-xxx.js: Development version. For programmers, there are good indentation and comments. Bigger
  2. jquery-xxx.min.js: The production version. Used in the program without indentation. Smaller size. The program loads faster.

JQuery object and JS object difference and conversion

  1. JQuery object is more convenient when operating.
  2. The JQuery object and js object methods are not universal.
  3. Convert between the two
    jq -> js: jq object [index] or jq object.get(index)
$div2[0].innerHTML = "cccccc";
$div2.get(0).innerHTML="dddddd";

Question: Why is index 0;
js-> jq: $(js object)

$(elementById).html("hi java");

Basic grammar

  1. Event binding
    js method:
let b1= document.getElementById("b1")
    b1.onclick=function () {
    
    
    alert("abcde");
}

jquery method

//1.获取b1按钮
$("#b1").click(function(){
    
    
       alert("abc");
 });
  1. Entry function
    js
window.onload=function() {
    
    
     let b1= document.getElementById("b1")
     b1.onclick=function () {
    
    
     alert("abcde");
   }
}

jquery

$(function () {
    
    
	           
});

The difference between window.onload and $(function):

window.onload can only be defined once, if it is defined multiple times, the latter will override the previous one. $(function) can be defined multiple times.
3. Style control: css method

// $("#div1").css("background-color","red");
//dom的颜色写法可以检查是否写对,当鼠标移动到背景颜色时,按住ctrl会变小手则说变编写正确
$("#div1").css("backgroundColor","pink");

Selector

Filter elements (tags) with similar characteristics

Basic selector

  1. Tag selector (element selector)
    syntax: $("html tag name") to get all elements matching the tag name
  2. id selector
    Syntax: $("#id的Attribute Value") Get the element that matches the specified id attribute value
  3. Class selector
    Syntax: $(".class attribute value") Get the element that matches the specified class attribute value
  4. Union selector:
    Syntax: $("Selector 1, Selector 2...") Get all elements selected by multiple selectors

Level selector

  1. Descendant selector
    Syntax: $("AB ") Select all B elements inside A element
  2. Sub-selector
    Syntax: $("A> B") selects all B sub-elements inside A element

Attribute selector

  1. Attribute name selector
    Syntax: $("A[attribute name]") contains the selector of the specified attribute
  2. Attribute selector
    Syntax: $("A[attribute name='value']") contains the selector whose specified attribute is equal to the specified value
  3. Compound attribute selector
    Syntax: $("A[attribute name='value'][]...") A selector containing multiple attribute conditions

Filter selector

  1. First element selector
    Syntax: :first Get the first element of the selected elements
  2. Last element selector
    Syntax: :last Get the last element of the selected elements
  3. Non-element selector
    Syntax: :not(selector) does not include elements with specified content
  4. Even selector
    Syntax: :even even number, counting from 0
  5. Odd selector
    Syntax: :odd odd number, counting from 0
  6. Equal to index selector
    Syntax: :eq(index) Specify index element
  7. Greater than index selector
    Syntax: :gt(index) Greater than the specified index element
  8. Less than index selector
    Syntax: :lt(index) is less than the specified index element
  9. Title selector
    Syntax: :header Get title (h1~h6) elements, fixed writing

Form filter selector

  1. Available element selector
    Syntax: :enabled Get available elements
  2. Unavailable element selector
    Syntax: :disabled to obtain unavailable elements
  3. Selected selector
    Syntax: :checked Get the selected element of single/check box
  4. Selected selector
    Syntax: :selected Get the selected element in the drop-down box

dom operation

  1. html(): Get/set the tag body content of the element <a><font>内容</font></a> --> <font>内容</font>
  2. text(): Get/set the plain text content of the element's tag body <a><font>内容</font></a> --> 内容
  3. val(): Get/set the value attribute value of the element.

General attribute operations

  1. attr(): Get/set the attributes of the element
  2. removeAttr(): remove attributes
  3. prop(): get/set the properties of the element
  4. removeProp(): What is the
    difference between attr and prop?
    If you are operating on the inherent attributes of the element, it is recommended to use prop , if you are operating on the element's custom attributes, it is recommended to use attr .

Operate the class attribute

  1. addClass(): add class attribute value
  2. removeClass(): delete the class attribute value
  3. toggleClass(): switch the class attribute
    toggleClass("one"):
    determine if class="one" exists on the element object, delete the attribute value one. If the element does not exist on the object
  4. css():

CRUD operations

  1. append(): The parent element appends the child element to the end.
    Object 1.append(Object 2): Add the object 2 to the inside of the object 1 element, and at the end
  2. prepend(): The parent element appends the child element to the beginning.
    Object 1.prepend (object 2): Adds the object 2 to the inside of the object 1 element, and at the beginning
  3. appendTo():
    object 1.appendTo(object 2): add object 1 to the inside of object 2, and at the end
  4. prependTo():
    object 1. prependTo (object 2): add object 1 to the inside of object 2, and at the beginning
  5. after(): Add the element to the back of the element
    Object 1.after (Object 2): Add the object 2 to the back of the object 1. Object 1 and Object 2 are brothers
  6. before(): Add the element to the front of the element
    Object 1.before (Object 2): Add the object 2 to the front of the object 1. Object 1 and Object 2 are brothers
  7. insertAfter()
    object 1.insertAfter(object 2): Add object 2 to the back of object 1. Object 1 and Object 2 are brothers
  8. insertBefore()
    object 1.insertBefore(object 2): Add object 2 to the front of object 1. Object 1 and Object 2 are brothers
  9. remove(): remove the element
    object. remove(): delete the object
  10. empty(): Empty all descendant elements of the element.
    Object.empty(): All the descendant elements of the object are emptied, but the current object and its attribute nodes are retained.

jquery advanced

Animation

Show and hide
  1. show([speed,[easing],[fn]]).
    parameter:
  2. speed: the speed of the animation. Three predefined values ​​("slow", "normal", "fast") or millisecond values ​​representing the duration of the animation (eg: 1000)
  3. easing: Used to specify the switching effect, the default is "swing", the available parameter "linear"
    swing: the effect is slow at first, fast in the middle, and slow at the end when the animation is executed.
    linear: The speed is constant when the animation is executed.
  4. fn: A function to be executed when the animation is completed, executed once for each element.
Slide show and hide way
  1. slideDown([speed],[easing],[fn])
  2. slideUp([speed,[easing],[fn]])
  3. slideToggle([speed],[easing],[fn])
Fade in and fade out display and hide methods
  1. fadeIn([speed],[easing],[fn])
  2. fadeOut([speed],[easing],[fn])
  3. fadeToggle([speed,[easing],[fn]])

Animation related functions

  //隐藏div
 function hideFn(){
    
    
     $("#showDiv").hide("slow","swing",function(){
    
    
         alert("隐藏了...")
     });
     //默认方式
     $("#showDiv").hide(5000,"swing");

     //滑动方式
     $("#showDiv").slideUp("slow");
     //淡入淡出方式
     $("#showDiv").fadeOut("slow");
 }

 //显示div
 function showFn(){
    
    
     $("#showDiv").show("slow","swing",function(){
    
    
         alert("显示了...")
     });

     //默认方式
     $("#showDiv").show(5000,"linear");
     //滑动方式
     $("#showDiv").slideDown("slow");

     //淡入淡出方式
     $("#showDiv").fadeIn("slow");
 }


 //切换显示和隐藏div
 function toggleFn(){
    
    

     //默认方式
     $("#showDiv").toggle("slow");
     //滑动方式
     $("#showDiv").slideToggle("slow");
     //淡入淡出方式
     $("#showDiv").fadeToggle("slow");
 }

Traverse

js traversal method

for (initialization value: loop end condition: step size)

Jq's traversal method

General method of traversal

$(function () {
    
    
    var citys=  $("#city li");
    //alert(citys);
    for (let i = 0; i <citys.length; i++) {
    
    
        alert(i+":"+citys[i].innerHTML);
    }
});
  1. jq object. Each (callback)
    syntax:
jquery对象.each(function(index,element){
    
    });
index:就是元素在集合中的索引
element:就是集合中的每一个元素对象
this:集合中的每一个元素对象

Callback function return value:

true:如果当前function返回为false,则结束循环(break)false:如果当前function返回为true,则结束本次循环,继续下次循环(continue)

Basic code:

$(function () {
    
    
    let citys = $("#city li");
    citys.each(function () {
    
    
        alert(this.innerHTML);
    })
});

$(function () {
    
    
    let citys = $("#city li");
    citys.each(function (index, element) {
    
    
       // alert(index+":"+element.innerHTML);
       if(element.innerHTML == "上海"){
    
    
            return true;
        }
        alert(index+":"+$(element).html());
    })
});
  1. $.each(object, [callback])
$(function () {
    
    
    let citys = $("#city li");
    $.each(citys,function () {
    
    
        alert($(this).html());
    })
});
  1. for...of: the method provided after jquery 3.0 version
    for (element object of container object)
$(function () {
    
    
    let citys = $("#city li");
    //此种方法只能在高版本的jquery中执行。
    for(li of citys){
    
    
        alert($(li).html());
    }
});

Event binding

  1. jQuery standard binding method
    jq object. Event method (callback function);
$(function () {
    
    
    $("#name").click(function () {
    
    
        alert("我被点击了");
    });
    //将移入移出事件绑定到jquery对象上
    $("#name").mouseout(function () {
    
    
        alert("mouse is outing");
    }).mouseover(function () {
    
    
        alert("mouse is over");
    });
    
    $("#name").focus(function () {
    
    
        alert(" get the focus ");
    })
    //若果是表单对象,我们则需要 用 表单对象.submit()来提交表单
});

Be sure to note that the form submission method uses the form object.submit();

  1. on bind event/off unbind
    jq object.on("event name", callback function)
    jq object.off("event name")
    If the off method does not pass any parameters, all events on the component will be unbound
$(function () {
    
    
   //1.使用on给按钮绑定单击事件  click
   $("#btn").on("click",function () {
    
    
       alert("我被点击了。。。")
   }) ;
   //2. 使用off解除btn按钮的单击事件
    $("#btn2").click(function () {
    
    
        //解除btn按钮的单击事件
        $("#btn").off("click");
        //将组件上的所有事件全部解绑
        $("#btn").off();
    });
});

jquery enhanced

Plug-in: Enhance the function of JQuery
Implementation mode:

  1. $.fn.extend(object)
    enhances the function of objects obtained through Jquery $("#id")
//增强对象的插件
$.fn.extend({
    
    
    check:function () {
    
    
        this.prop("checked",true);
    },
    uncheck:function () {
    
    
        this.prop("checked",false)
    }
});
$(function () {
    
    
    $("#btn-check").click(function () {
    
    
        $("input[type='checkbox']").check();
    });
    $("#btn-uncheck").click(function () {
    
    
        $("input[type='checkbox']").uncheck();
    })
});
  1. $.extend(object)
    enhances the function of JQeury object itself$/jQuery
$.extend({
    
    
    max:function (a,b) {
    
    
        return a>=b ? a:b;
    },
    min:function (a,b) {
    
    
        return a<=b ? a:b;
    }
});
var max = $.max(3,4);
alert(max);
let min = $.min(7,6);
alert(min);

Guess you like

Origin blog.csdn.net/xueshanfeitian/article/details/110646317