07 front-end --JQuery

A, JQuery Introduction

  1. jQuery is a lightweight, multi-browser compatible JavaScript library.
  2. jQuery makes it easier for users to handle HTML Document, Events, achieve animation effects, easily interact with Ajax, JavaScript can greatly simplify programming. Its purpose is: "Write less, do more."

Two, JQuery advantage

  1. A lightweight JS framework. jQuery core js file only a few dozen kb, will not affect the page loading speed.
  2. Rich DOM selectors, jQuery selection Used easy to use, for example, to find adjacent elements of a DOM object, JS could write several lines of code, and one line of code jQuery to get, then you want a table such as interlaced color, jQuery also get line of code.
  3. Chain expression. jQuery's chaining multiple operations can be written in a single line of code, the more concise.
  4. Events, styles, animation support. jQuery also simplifies the operation css js code readability and also stronger than js.
  5. Ajax operations support. AJAX jQuery simplifies operation, only the rear end of a return communication JSON string format can be done in the front end.
  6. Cross-browser compatible. jQuery basically compatible with the major browsers now, no longer compatible browser issues and headache.
  7. Plug-in extension development. jQuery has a wealth of third-party plug-ins, such as: tree menu, date control, image transition plug-ins, pop-ups, etc. The basic component on the front page has a corresponding plug-in, and do it with jQuery plug-in effects stunning, and can be according to their need to rewrite and package plug-ins, simple and practical.

Three, JQuery content

  1. Selector
  2. Filters
  3. Style operations
  4. Text manipulation
  5. Property operations
  6. Document Actions
  7. event
  8. Animation
  9. Plug
  10. each、data、Ajax

Download link: jQuery official website

Chinese Documentation: jQuery document the AP Chinese

Four, JQuery objects

  • jQuery object object is the packaging after the adoption of jQuery DOM object created

  • jQuery object is unique to jQuery. If an object is a jQuery object , then you can use jQuery in the way: for example, $ ( "# i1") html ().

    $("#i1").html()的意思是:获取id值为 i1的元素的html代码。其中 html()是jQuery里的方法。
    相当于: document.getElementById("i1").innerHTML;
  • Although the jQuery对象packaging DOM对象produced later, but jQuery对象can not use DOM对象any method, empathy DOM对象did not use jQueryin the method.

Five, JQuery create objects

A convention, we declare a jQuery object variable in the time before the variable name with $:

var $variable = jQuery对像
var variable = DOM对象

Jq conversion between the object and the DOM object:

$variable[0] //jQuery对象转成DOM对象
$(dom) //DOM转成JQ对象

jQuery objects and DOM objects using:

$("#i1").html(); //jQuery对象使用jQuery的方法
$("#i1")[0].innerHTML;// DOM对象使用DOM的方法

Six, JQuery's basic grammar

6.1 The basic element selectors

1.id选择器
$("#a"); //选择id属性值为a的jq对象(一个列表$("#a")[0]是一个DOM对象)

2.标签选择器
$("div"); //选择div标签

3.class选择器
$(".a"); //选择class类为a的标签

4.配合使用
$("div.c1");  //选择div标签中,类属性值为c1的div标签

5.所有元素选择器
$("*"); //选择所有标签元素(列表形式返回)

6.组合选择器
$("#a, .b, div"); //找到id属性值为a、类为b、标签div的这些标签

7.层级选择器
$("x y"); // x的所有后代y(子子孙孙)
$("x > y"); // x的所有儿子y(儿子)
$("x + y"); // 找到所有紧挨在x后面的y
$("x ~ y"); // x之后所有的兄弟y

6.2 The basic elements of a filter

:first // 第一个
:last // 最后一个
:eq(index)// 索引等于index的那个元素
:even // 匹配所有索引值为偶数的元素,从 0 开始计数
:odd // 匹配所有索引值为奇数的元素,从 0 开始计数
:gt(index)// 匹配所有大于给定索引值的元素
:lt(index)// 匹配所有小于给定索引值的元素
:not(元素选择器)// 移除所有满足not条件的标签
:has(元素选择器)// 选取所有包含一个或多个标签在其内的标签(指的是从后代元素找)

Example 1:

$("div:first") // 选择html中第一个div元素

$("div:last")// 选择html中最后一个div元素

$("div:eq(5)")// 找到html中的第5个div元素

$("div:even")// 匹配所有索引值为偶数的div元素,从0开始计数

$("div:odd")// 匹配所有索引值为奇数的div元素,从 0 开始计数

$("div:gt(2)")// 匹配所有大于给定索引值的元素

$("div:lt(2)")// 匹配所有索引小于2的div标签元素

$("div:not(.c1)")// 找到所有不包含c1样式类的div标签

$("div:not(:has(a))")// 找到所有后代中不含a标签的div标签

Seven, attribute selectors

Attribute selector syntax:

[attribute] //需要选择的属性
[attribute=value]// 属性等于
[attribute!=value]// 属性不等于

Example:

<input type="text">
<input type="password">
<input type="checkbox">
    
$("input[type='checkbox']");// 取到checkbox类型的input标签
$("input[type!='text']");// 取到类型不是text的input标签

Eight filter method

The next element:

$("div").next() //div标签的下一个并集元素

$("div").nextAll() // div标签的所有的并集元素
$("div").nextUntil("a") //选择div下面的的并集元素,一直到与它并集的a标签元素结束,不包括a元素

On an element:

$("div").prev() //div标签并集的上一个元素
$("div").prevAll() //div标签并集的上层所有元素
$("div").prevUntil("a") // div并集的上面的元素,一直到a元素,不包括a元素

Father element:

$("#id").parent()//查找当前元素的父级元素,
$("#id").parents()  // 查找当前元素的所有的父辈元素
$("#id").parentsUntil("匹配的元素") // 查找当前元素的所有的父辈元素,直到遇到匹配的那个元素为止。

Sons and brothers elements:

$("#id").children();// 儿子们
$("#id").siblings();// 兄弟们

8.1 Find (find)

Search for all elements that match the specified expression. This function is to find a good way to descendant elements being processed.

$("div").find("p") //等价于 $("div p")

8.2 Filter (filter)

Filter out elements that match the specified expression collection. This method is used to narrow down. Multiple expressions are separated by commas.

$("div").filter(".c1")  // 从结果集中过滤出有c1样式类的div元素
// 等价于 $("div.c1")

supplement:

.first() // 获取匹配的第一个元素
.last() // 获取匹配的最后一个元素
.not() // 从匹配元素的集合中删除与指定表达式匹配的元素
.has() // 保留包含特定后代的元素,去掉那些不含有指定后代的元素。
.eq() // 索引值等于指定值的元素

Nine, form elements selector

:text //找到所有的text的input元素

:password //找到所有的password的input元素

:file //找到所有的file的input元素

:radio //找到所有的radio的input元素

:checkbox //找到所有的checkbox的input元素

:submit //找到所有的submit的input元素

:reset //找到所有的reset的input元素

:button //找到所有的button的input元素

Example 1:

$(":text")  //找到所有的text的input元素

$(":password")  //找到所有的password的input元素

$(":file")  //找到所有的file的input元素

$(":radio")  //找到所有的radio的input元素

$(":checkbox")  //找到所有的checkbox的input元素

$(":submit")  //找到所有的submit的input元素

$(":reset")  //找到所有的reset的input元素

$(":button")  //找到所有的button的input元素

Ten, form object properties

:enabled //表单对象是可用,默认可用

:disabled //表单对象不可用,设置了表示这个对象不可用

:checked //对象默认被选中的元素,不需要人为的去选择(checkbox和radio用)

:selected // 找到对象已经被选中的元素

Example 1: Find the available input tag

<form>
  <input name="email" disabled="disabled" />
  <input name="id" />
</form>

$("input:enabled")  // 找到可用的input标签,找到的是name=“id”的input元素

Example 2: Find the selected option

<select id="s1">
  <option value="beijing">北京市</option>
  <option value="shanghai">上海市</option>
  <option selected value="guangzhou">广州市</option>
  <option value="shenzhen">深圳市</option>
</select>

$(":selected")  // 找到被选中的option

XI operation tag

11.1 operating style (CSS)

addClass();// 添加指定的CSS类名。
removeClass();// 移除指定的CSS类名。
hasClass();// 判断样式存不存在
toggleClass();// 切换CSS类名,如果有就移除,如果没有就添加。

####实例:
$("#a").addClass("d");//为a类的标签元素添加d类
$("#a").removeClass("d") //a类的标签元素移除d类
$("#a").hasClass("d");//a类的标签元素判断d类存不存在
$("#a").toggleClass("d") //a类元素是否有b类,有删除,没有添加

Example:

DOM对象:
css("color","red")//DOM操作:tag.style.color="red"

JQ对象:
$("p").css("color", "red"); //将所有p标签的字体设置为红色

11.2 Operating position

offset()// 获取匹配元素在当前窗口的相对偏移或设置元素位置
position()// 获取匹配元素相对父元素的偏移
scrollTop()// 获取匹配元素相对滚动条顶部的偏移
scrollLeft()// 获取匹配元素相对滚动条左侧的偏移

######实例:
$("#a").offset()
$("#a").position()
$("#a").scrollTop()
$("#a").scrollLeft()

.offset()Method allows us to retrieve one element relative to the current position of the document (document) is.

And the .position()difference is: .position()with respect to a displacement relative to the parent element.

Size of the operating 11.3

height()
width()
innerHeight()
innerWidth()
outerHeight()
outerWidth()

####实例:
$("#a").height() //当前元素的高度
$("#a").width() //当前元素的宽度
$("#a").innerWidth() //当前元素内部内容占的宽度
$("#a").innerHeight()//当前元素内部内容占的高度
$("#a").outerHeight()//
$("#a").outerWidth()

11.4 text manipulation

HTML code:

html()// 取得第一个匹配元素的html内容
html(val)// 设置所有匹配元素的html内容

####实例:
$("#a").html()//取得id为a的元素的hrml的所有内容
$("#a").html("hello") //将id为a的元素的html内容改为hello
$("#a").html("<p>hello</p>")//可以直接上标签对象

Text Value:

text()// 取得所有匹配元素的内容
text(val)// 设置所有匹配元素的内容

####实例:
$("#a").text()//取得id为a的元素的文本内容
$("#a").text("hello") //将id为a的元素的文本内容改为hello

#####报错
$("#a").text("<p>hello</p>")//报错

value:

val()// 取得第一个匹配元素的当前值
val(val)// 设置所有匹配元素的值
val([val1, val2])// 设置多选的checkbox、多选select的值

###实例:
$("#a").val()//获取id为a的元素的第一个文本内容
$("#a").val("beijing")//设置匹配的值

$("[name='hobby']").val(['basketball', 'football']);
$("#s1").val(["1", "2"])
//设置name属性为hobby的元素,value为basketball或者football的元素的value为1和2

Example: to get the value of the selected checkbox or radio

<label for="c1">女</label>
<input name="gender" id="c1" type="radio" value="0">
<label for="c2">男</label>
<input name="gender" id="c2" type="radio" value="1">
    
    
###实例
$("innput[name="gender"]:checked").val()

11.5 Operating property

With ID or other custom properties

attr(attrName)// 返回第一个匹配元素的属性值
attr(attrName, attrValue)// 为所有匹配元素设置一个属性值
attr({k1: v1, k2:v2})// 为所有匹配元素设置多个属性值
removeAttr()// 从每一个匹配的元素中删除一个属性


####实例:
$("div").attr("name") //获取div元素的name属性的值
$("div").attr("age","18")//设置div元素的age属性值
$("a").attr({"name":"cecilia","age":"18"}) //对a元素进行一次性赋值,用字典的形式
$("a").removeattr("name") //移除a元素的name属性

For checkbox and radio

prop() // 获取属性
removeProp() // 移除属性


####实例:
$("input").prop("checked") // 返回的十布尔值
$("input").prop("checked",false) //将input元素的checked属性设为false
$("input").attr("checked") //查看inoput元素的checked的属性值

note:

When the bug will be checkbox assignment using attr 1.x and 2.x versions of the jQuery, the 3.x version of jQuery in it is not the problem. For compatibility, we try to use a specific prop (when dealing checkbox and radio), do not use the attr ( "checked", "checked").

<input type="checkbox" value="1">
<input type="radio" value="2">
<script>
  $(":checkbox[value='1']").prop("checked", true);
  $(":radio[value='2']").prop("checked", true);
</script>

The difference between 11.6 porp and attr

attr full name attribute (attribute)

Full prop property (attribute)

Although there are properties, but they are referring to is not the same attributes, attribute attr referring to the HTML tag attributes, and prop referring to the DOM object properties, can be considered attr be explicit, implicit and prop.

Example 1:

<input type="checkbox" id="i1" value="1">
    
    
### 测试1
$("#i1").attr("checked")  // undefined
$("#i1").prop("checked")  // false

可以看到attr获取一个标签内没有的东西会得到undefined,而prop获取的是这个DOM对象的属性,因此checked为false。


### 测试2
<input type="checkbox" checked id="i1" value="1">
$("#i1").attr("checked")   // checked
$("#i1").prop("checked")  // true
这已经可以证明attr的局限性,它的作用范围只限于HTML标签内的属性,而prop获取的是这个DOM对象的属性,选中返回true,没选中返回false。

Test 2: The difference for custom attributes, attr and prop of:

<input type="checkbox" checked id="i1" value="1" me="自定义属性">
    

### 测试:
$("#i1").attr("me")   // "自定义属性"
$("#i1").prop("me")  // undefined
可以看到prop不支持获取标签的自定义属性。

to sum up:

  1. For the label to see some of the attributes and custom attributes with attr
  2. For returns a Boolean value, such as checkbox, radio and the option of whether to have been selected by prop.

11.7 Document Processing

(After the last child node) to add a tag to the inside of the last specified element

$(A).append(B)// 把B追加到A
$(A).appendTo(B)// 把A追加到B

Adding an element to the tag (before the first child node) inside the signature specified element most

$(A).prepend(B)// 把B前置到A
$(A).prependTo(B)// 把A前置到B

Appended to the outside of the specified element (last sibling)

$(A).after(B)// 把B放到A的后面
$(A).insertAfter(B)// 把A放到B的后面

Element added to the outside of the designated top (top of the first sibling node)

$(A).before(B)// 把B放到A的前面
$(A).insertBefore(B)// 把A放到B的前面

Remove and empty elements

remove()// 从DOM中删除所有匹配的元素。

empty()// 删除匹配的元素集合中所有的子节点。
$(".b").empty() //删除所有有b类属性的列表集合

XII event

12.1 Common events

click(function(){...}) // 鼠标单击事件

hover(function(){...}) //鼠标移动到位置事件

blur(function(){...}) //失去焦点事件

focus(function(){...})//得到焦点事件

change(function(){...})//改变标签域内容事件

keyup(function(){...})//触发键盘事件

12.2 event binding

  • events: Event
  • selector: selector (optional)
  • function: event handler
.on( events [, selector ],function(){})


###实例:
###方法一:
$("button").on("click",function () {
        ·······
    })

###方法二:
 $("button").click(function () {
     ·········
     })

12.3 out of events

off()The method used to remove .on()event handlers bound.

  • events: Event
  • selector: selector (optional)
  • function: event handler
.off( events [, selector ][,function(){}])

12.4 prevent the implementation of subsequent events

  1. return false; // 常见阻止表单提交等
  2. e.preventDefault();

Example:

<form>
    <input type="text" value="" id ="id"><span class="hid">不能为空</span>
    <br>
    <input type="submit" value="拜拜!" id="sub">
</form>
<script>
    $("#sub").on("click",function (e) {
           var data= $("#id").val();
           if(!data.trim()){
               $(".hid").removeClass("hid");
               //第一种阻止事件的方法
               // return false
                //第二种阻止事件的方法
               e.preventDefault()
           }
    })

Friendly reminder: as the event click, keydown and other DOM defined, we can use the .on()method to bind an event, but hoveran event that can not be used jQuery defined .on()method to bind up.

Want to use the event delegation manner binding hover event handler, you can reference the following code to bind event in two steps:

<button>点击这里</button>
<script>
    $("body").on("click","button",function () {
        console.log(123)
    })
</script>

12.5 organization event bubbling

<style>
    #a{
width: 500px;
height: 500px;
background-color: red;
}
#b{
width: 400px;
height: 400px;
background-color: green;
}
#c{
width: 200px;
height: 200px;
background-color: black;
}
</style>
<script>
        $(function(){
        $("#a").on("click",function () {
            alert("第一")
        });
        $("#b").on("click",function (e) {
            alert("第er");
            e.stopPropagation();//阻止事件冒泡
        });
        $("#c").on("click",function (e) {
            alert("第san");
            e.stopPropagation();//阻止事件冒泡,因为这个div元素十最小的子标签,锁以点击它的时候,会一直连带的触发他的爸爸和爷爷,所以需要组织它事件的执行
        });
    })
</script>

<div id="a">
    <div id="b">
        <div id="c"></div>
</div>

12.6 page loads

Bind a function to be executed when the DOM is ready to query and manipulate. This module is the most important event of a function, because it can greatly improve the response speed of the web application. (Window.onload () waits for all the html elements are loaded)

Two way (Method 1):

$(document).ready(function(){
// 在这里写你的JS代码...
})

(Method B): shorthand

$(function(){
// 你在这里写你的代码
})

Stop event bubbling instance:

# 这样写script代码
$(document).ready(function(){
    $("#a").on("click",function () {
        alert("第一")
    });
    $("#b").on("click",function (e) {
        alert("第er")
        e.stopPropagation()
    });
    $("#c").on("click",function (e) {
        alert("第san");
        e.stopPropagation()
    });
})

12.7 JQ page load difference DOM page load

  • window.onload () function can be called after covering the phenomenon, must wait for the image resource loading is complete
  • This entry jQuery function has no coverage phenomenon, after the document has finished loading you can call (recommended to use this function)

12.8 event delegation

Event delegate is the principle event bubbling through the use of the parent tag to capture the event sub tag.

Example: set click events through most of the parent body tag, so that all the button html have this event

<script>
    $("body").on("click","button",function () {
        console.log(123)
    })

</script>

XIII, animation

// 基本
show([s,[e],[fn]])
hide([s,[e],[fn]])
toggle([s],[e],[fn])

// 滑动
slideDown([s],[e],[fn])
slideUp([s,[e],[fn]])
slideToggle([s],[e],[fn])

// 淡入淡出
fadeIn([s],[e],[fn])
fadeOut([s],[e],[fn])
fadeTo([[s],o,[e],[fn]])
fadeToggle([s,[e],[fn]])

// 自定义(了解即可)
animate(p,[s],[e],[fn])

Thumbs effects:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>点赞动画示例</title>
  <style>
    div {
      position: relative;
      display: inline-block;
    }
    div>i {
      display: inline-block;
      color: red;
      position: absolute;
      right: -16px;
      top: -5px;
      opacity: 1;
    }
  </style>
</head>
<body>

div id="d1"点赞/div
<script src="jquery-3.2.1.min.js"></script>
<script>
  $("#d1").on("click", function () {
    var newI = document.createElement("i");
    newI.innerText = "+1";
    $(this).append(newI);
    $(this).children("i").animate({
      opacity: 0
    }, 1000)
  })
</script>
</body>
</html>

Fourteen, each

jQuery.each(collection, callback(indexInArray, valueOfElement)):

Description: A general iterative function, which can be used seamlessly and iterative array of objects. Arrays and array-like objects to a number of iterations indexed by the length of the property (e.g., a function of the parameter object), from 0 to length - 1. Other objects to iterate through the property names.

li =[10,20,30,40]
$.each(li,function(i, v){
  console.log(i, v);//index是索引,ele是每次循环的具体元素。
})

###输出
010
120
230
340

.each(function(index, Element)):

Description: traversing a jQuery object, perform a match function for each element.

.each()Iterative methods for each element jQuery DOM object. Each time the callback is executed, the number of cycles the current is passed as a parameter (counting from 0). Since the callback is triggered in the context of the current DOM element as the context, so the key thisis always pointing to this element.

// 为每一个li标签添加foo
$("li").each(function(){
  $(this).addClass("c1");
});

Note: jQuery method returns a jQuery object, through the elements of the set jQuery - referred implicit iterative procedure. When this happens, it usually does not need to explicitly circulation .each()method:

In other words, the above example is not necessary to use each () method, like this directly written on it:

$("li").addClass("c1");  // 对所有标签做统一操作

Note: You can use during traversal return falseearly termination of each cycle.

Termination of each cycle:return false

Guess you like

Origin www.cnblogs.com/xichenHome/p/11689433.html