JQuery front-end basis

[TOC]

jQuery Introduction

1, jQuery is a lightweight, multi-browser compatible JavaScript library.

2, jQuery allows users to more easily handle HTML Document, Events, achieve animation effects, easily interact with Ajax, JavaScript can greatly simplify programming.

Advantage:

1, is a lightweight JS framework. jQuery core js file only a few dozen kb, will not affect the page loading speed.

2, many tasks can get a line of code.

3, chain expression. You can put the whole code written in a row, more concise.

4, operability and readability more than js

5, known as a full major browsers compatible

6, strong expansion. Plug addition of good, simple and practical.

jQuery content:

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

jQuery object

jQuery object is an object produced after packaging DOM objects by jQuery. jQuery object is unique to jQuery. If an object is a jQuery object , then it can use jQuery in the way: 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对象can not be used jQueryin the method.

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的方法

jQuery basic syntax: $ (selector) .action ()

jQuery selector

The basic selector

id selector: $ ( "# id")

Tag selector: $ ( "tagName")

class selector: $ ( "className.")

In combination: $ ( "div.c1") // find the div tag has c1 class class

All element selector: $ ( "*")

Combined selector: $ ( "# id, .className, tagName")

Level Selector:

x and y may be any selector

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

Basic Filters:

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

Example:

$("div:has(h1)")// 找到所有后代中有h1标签的div标签
$("div:has(.c1)")// 找到所有后代中有c1样式类的div标签
$("li:not(.c1)")// 找到所有不包含c1样式类的li标签
$("li:not(:has(a))")// 找到所有后代中不含a标签的li标签

Custom frame mode, and the pop-up achieved using jQuery hidden features.

Attribute Selector:

[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标签

Form Filter:

:text
:password
:file
:radio
:checkbox

:submit
:reset
:button

Example:

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

Form object properties:

:enabled
:disabled
:checked
:selected

Example:

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

$("input:enabled")  // 找到可用的input标签

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

Filter Method

The next element:

$("#id").next()
$("#id").nextAll()
$("#id").nextUntil("#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();// 兄弟们

Seek

$("div").find("p")  //找div的后代中所有的p,可写成  $("div p")

filter

$("div").filter(".c1")  // 从结果集中过滤出有c1样式类的。可写成 $("div.c1")

supplement

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

Handling label

Style operations

Style class

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

Example: Refer to switch light mode and frame

CSS

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

Example:

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

Operating position

offset()// 获取匹配元素在当前窗口的相对偏移或设置元素位置
position()// 获取匹配元素相对父元素的偏移
scrollTop()// 获取匹配元素相对滚动条顶部的偏移
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:

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

Text manipulation

HTML code:

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

Text Value:

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

value:

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

E.g:

<input type="checkbox" value="basketball" name="hobby">篮球
<input type="checkbox" value="football" name="hobby">足球

<select multiple id="s1">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

Settings:

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

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

Property operations

An ID or other custom properties:

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

For checkbox and radio

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

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.

in conclusion:

  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.

Document processing

Add to the specified element inside the latter

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

Specified element added to the inside front of the

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

Specified element added to the outside behind

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

Specified element added to the outside in front of the

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

Remove and empty elements

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

replace

replaceWith()
replaceAll()

clone

clone()// 参数

event

Common events

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

keydown event and keyup combination example:

hover event Example:

Real-time monitoring input input values ​​change example:

Event binding

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

Remove event

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

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

  • events: Event
  • selector: selector (optional)
  • function: event handler

Prevent the implementation of subsequent events

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

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.

Stop event bubbling

<!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>

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(){
// 你在这里写你的代码
})

Event delegates

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

Example:

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

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

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

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是每次循环的具体元素。
})

Output:

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:

It can be used during traversal return falseended prematurely each cycle

Guess you like

Origin www.cnblogs.com/allenchen168/p/11902170.html