The distal end 49 of the learning jQuery 6

A, jQuery Introduction

1 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."

2. jQuery objects

jQuery object is an object produced after packaging DOM objects by jQuery.

jQuery jQuery object is unique.

If an object is a jQuery object, then in jQuery methods it can use: for example, $ ( "# i1") html ().

$("#i1").html()It means: id value acquiring i1html code elements. Which html()is in the jQuery method. It is equivalent to: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.

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

var $variable = jQuery对像
var variable = DOM对象
$variable[0]  //jQuery对象转成DOM对象

Take the example above example, using jQuery objects and DOM object:

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

Second, the basic grammar

$(selector).action()

1. Select the device (look for the label)

1.1 Basic selector

  1. id selector:

    $('#d1')
  2. Tag selector

    $('div')
  3. class selector

    $('.c1')
  4. With the use of

    $('div.c1')  // 找到继承c1类的div标签
  5. All elements of selectors

    $('*')
  6. Combination selector

    $('#d1, .c1, div')

1.2 level selector (descendant selectors)

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

1.3 Attribute selectors

[attribute]
[attribute='value']  // 属性等于
[attribute!='value']  // 属性不等于

2. Filter

For further screening in the choice of the label.

2.1 Basic filters

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

// 举例:
$('div:has("d1")')  // 查找含有id=d1属性的div标签

2.2 Form Filter

Screening different types of form input tag:

//筛选input标签中,不同type类型的input标签
:text  // [type = 'text']
:password
:file
:radio
:checkbox
:submit
:reset
:button  // :button 不仅可以选中type='button'的input标签,也可以直接选中button标签,而$('button')只能选中button标签。

Simple Object Form Properties options:

:enabled
:disabled
:checked  // checked 会将 selected 也选择到
:selected  // 而selected只能选择selected标签

2.3 Filter Method

Filter method to the jQuery object directly. Method name () method used.

The next element:

$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#i2")  // 不包含#i2标签本身

On an element:

$("#id").prev()
$("#id").prevAll()  // 同级别的
$("#id").prevUntil("#i2")

Father element:

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

Sons and brothers elements:

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

Find Method:

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")

Screening methods:

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样式类的

supplement:

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

$('div span').first() == $('div span:first')

3. Operation label

3.1 Class Action

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

$('div').addclass('red_bg')  // 给div标签添加'red_bg'类

3.2 style operation

CSS Styles

p.style.color='red'  ==  $('p').css('color','red');

Position of the operation 3.3

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

3.4 size

Gets the label of an object's properties

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

3.5 text manipulation

HTML code:

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

Text Value:

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

value:

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

Settings:

$("[name='hobby']").val(['basketball', 'football']);
$("#s1").val(["1", "2"])

Example:

Gets 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">

can use:

$("input[name='gender']:checked").val()

3.6 attribute manipulation

An ID or other custom properties:

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

For checkbox and radio

prop()  // 获取属性
removeProp()  // 移除由 prop() 方法设置的属性。不要使用该方法来移除诸如 style、id 或 checked 之类的 HTML 属性。

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>

prop and attr difference:

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, it can be considered attr be explicit, implicit and prop.

for example:

<input type="checkbox" id="i1" value="1">

For the above code,

$("#i1").attr("checked")  // undefined
$("#i1").prop("checked")  // false

Attr you can see not get a label things will get undefined, while prop acquired property is the DOM object, so checked as false.

If you replace the following code:

<input type="checkbox" checked id="i1" value="1">

Then execute:

$("#i1").attr("checked")   // checked
$("#i1").prop("checked")  // true

This has to prove attr limitations, its scope is limited to properties within the HTML tags, and prop acquisition is the property of the DOM object, returns true selected, not selected returns false.

Then look again for custom attributes, attr and prop what is the difference:

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

Execute the following code:

$("#i1").attr("me")   // "自定义属性"
$("#i1").prop("me")  // undefined

You can see the prop does not support getting custom tag attributes.

3.7 Document Processing

Appended to the inside of the specified element

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

Added to the front of the interior of the specified element

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

Appended to the outside of the specified element

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

Added to the front outside of the specified element

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

Remove and empty elements

remove()  // 从DOM中删除所有匹配的元素。
empty()  // 删除匹配的元素集合中所有的子节点。

example:

Click the button to add a row of data in the table.

Click on each line Delete button to delete the current line data.

replace

replaceWith()
replaceAll()

clone

clone()// 参数

Example Cloning:

<!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>
    #b1 {
      background-color: deeppink;
      padding: 5px;
      color: white;
      margin: 5px;
    }
    #b2 {
      background-color: dodgerblue;
      padding: 5px;
      color: white;
      margin: 5px;
    }
  </style>
</head>
<body>

<button id="b1">屠龙宝刀,点击就送</button>
<hr>
<button id="b2">屠龙宝刀,点击就送</button>

<script src="jquery-3.2.1.min.js"></script>
<script>
  // clone方法不加参数true,克隆标签但不克隆标签带的事件
  $("#b1").on("click", function () {
    $(this).clone().insertAfter(this);
  });
  // clone方法加参数true,克隆标签并且克隆标签带的事件
  $("#b2").on("click", function () {
    $(this).clone(true).insertAfter(this);
  });
</script>
</body>
</html>

4. Event

4.1 Common events

click(function(){...})
hover(function(){...})
blur(function(){...})
focus(function(){...})
change(function(){...})
keyup(function(){...})

hover event Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>苍茫的天涯是我的哎,绵绵的青山脚下一片海!</p>

<script src="jQuery-3.3.1.js">
</script>
<script>
    $('p').hover(  // 鼠标悬浮上去的时候触发。如果你只写了一个函数,  那么悬浮和移开都触发这个
        function () {
            alert('来啦,老弟')
        },
        function () {
            alert('慢走哦~')
        }
    )
</script>
</body>
</html>

4.2 Event binding

// 方法1
.on(events [, selector ],function(){})

// 方法2
obj.onclick = function(){
    ...
}

events: Event

selector: selector (optional)

function: event handler

note:

Events like 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. 4.1 There hover example.

4.3 removal event

.off(events [, selector ][,function(){}])

events: Event

selector: selector (optional)

function: event handler

4.4 to prevent the implementation of subsequent events

Prevent some subsequent events are automatically executed execution

// 方法1
return false; // 常见阻止表单提交等

// 方法2
e.preventDefault();

example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阻止默认事件</title>
</head>
<body>

<form action="">
    <button id="b1">点我</button>
</form>

<script src="jquery-3.3.1.min.js"></script>
<script>
    $("#b1").click(function (e) {
        alert(123);
        // 方法1
        //return false;
        // 方法2
        e.preventDefault();
    });
</script>
</body>
</html>

4.5 prevent bubbling event

Stop for a tag event triggers the same type of event of its parent tag.

can use:

e.stopPropagation()

For example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阻止事件冒泡</title>
</head>
<body>
<div>
    <p>
        <span>点我</span>
    </p>
</div>
<script src="jquery-3.3.1.min.js"></script>
<script>
    $("span").click(function (e) {
        alert("span");
        e.stopPropagation();
    });

    $("p").click(function () {
        alert("p");
    });
    $("div").click(function () {
        alert("div");
    })
</script>
</body>
</html>

4.6 page load

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.

Two way:

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

Shorthand:

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

The difference between the window.onload

  • 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)

4.7 event delegation

Event delegate is the principle event bubbling through the use of the parent tag to capture the event sub tag. Otherwise, if dynamically generate a new label with js, this label is not binding event of the original HTML text.

Example:

Each row of the table Edit and Delete buttons can trigger a corresponding event.

$("table").on("click", ".delete", function () {
  // 删除按钮绑定的事件
})

Guess you like

Origin www.cnblogs.com/bowendown/p/11892384.html