Front-end Architect 01_JQuery

1 Quick Start with jQuery

1.1 What is jQuery

It is an open source JavaScript library.

Common JavaScript libraries: jQuery, Prototype, ExtJS, Mootools, YUI, etc.

The core concept of jQuery: write less, do more (write less, do more).

Features of jQuery:

  • jQuery is a lightweight script and its code is very small.
  • The syntax is concise and easy to understand, the learning speed is fast, and the documentation is rich.
  • Supports properties and selectors defined by CSS1~CSS3.
  • Cross-browser, supported browsers include IE6~IE11 and Chrome, etc.
  • The separation of JavaScript scripts and HTML codes is realized, which facilitates later editing and maintenance.
  • Plug-ins are abundant and more functions can be extended through plug-ins.

1.2 Download jQuery

jQuery download link

  • jQuery 1.x series: Updates have been stopped and support for early browsers has been maintained. The final version is jQuery 1.12.4.
  • jQuery 2.x series: has stopped updating and no longer supports IE6~8 browsers, making it more lightweight. The final version is jQuery2.2.4.
  • jQuery 3.x series: only supports the latest browsers, so this version is generally not used unless specifically requested.

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

  • minified compressed production version,
  • uncompressed uncompressed development version

Open the link -> right click, save webpage as (or Ctrl + S) -> select the save directory

1.3 Using jQuery

<!-- 方式1:引入本地下载的jQuery -->
<script src="jquery-1.12.4.min.js"></script>
<!-- 方式2:通过CDN(内容分发网络)引入jQuery -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • Method 1 introduces the jquery-1.12.4.min.js file in the current directory.
  • Method 2 takes advantage of the public CDN to speed up the loading of jQuery files.

Create an element in the HTML page with the text "test" and the attribute (align="center") <h2>.

// 原生JavaScript的实现方式
var h2 = document.createElement('h2'); 	// 创建h2元素节点
var text = document.createTextNode('测试'); // 创建文本节点
var attr = document.createAttribute('align');	// 创建属性节点
attr.value = 'center'; 			// 为属性节点赋值
h2.setAttributeNode(attr);  	// 为h2元素添加属性节点
h2.appendChild(text); 		// 为h2元素添加文本节点
// 将h2节点追加为body元素的子节点
document.querySelector('body').appendChild(h2);

// jQuery的实现方式
$('<h2 align="center">测试</h2>').appendTo('body');
  • The dollar sign "$" represents the jQuery class.
  • " $()" is equivalent to " jQuery()", which is jQuery's constructor. By passing an element to the constructor, an element object can be created.

2 element operations

2.1 jQuery object

jQuery object: It is a layer of packaging for DOM objects.

Function: It simplifies the complexity of DOM operations and improves program development efficiency through a series of shortcut functions provided by itself.

Problems solved: Compatibility issues with different browsers.

// 创建一个jQuery对象,该对象包装了document对象
var $doc = $(document);
// 在控制台中输出jQuery对象
console.log($doc);       
  • $(document)Represents converting the document object into a jQuery object.
  • You console.log()can view its internal structure.
  • There are 3 elements inside the jQuery object.
  • The element with subscript 0 represents its internal DOM object, that is, the document object.
  • length represents the number of internal DOM objects. One jQuery object can wrap multiple DOM objects.
  • You __proto__can view the properties and methods of the object's prototype (that is, jQuery itself).

2.2 jQuery selector

jQuery selectors are a way of manipulating HTML elements similar to the mechanism of CSS selectors.

Advantages: DOM elements can be easily obtained.

The basic syntax of jQuery selector: $(selector).

According to the different methods of obtaining selectors, they can be roughly divided into the following categories.

  • basic selector
  • level selector
  • Basic filter selector
  • Content selector
  • visibility selector
  • attribute selector
  • Child element selector
  • form selector
2.2.1 Basic selectors

The basic selectors in jQuery are commonly used: tag selector, class selector and ID selector.

Selector Function description Example
element Matches all elements based on the specified element name $("li")Select all <li>elements
.class Matches all elements based on the specified class name $(".bar")Select all elements with class bar
#id Matches an element based on the specified id $("#btn")Select the element with id btn
selector1,selector2,… Get multiple elements at the same time $("li,p,div")Get all <li>、<p>和<div>elements at the same time
2.2.2 Level selector

The hierarchical selector uses some specified symbols, such as spaces, >, + and ~ to complete the acquisition of multi-level elements.

Selector Function description Example
selector selector1 Select all descendant elements under the ancestor element $("div .test")Select <div>all elements with class name test (multi-level)
parent > child Get all child elements under the parent element $(".box >.con")Select all child elements with the class name con under the class name box (first level)
prev + next Get the next sibling element immediately adjacent to the current element $("div + .title")Get <div>the next sibling node named title
prev~siblings Get all sibling elements after the current element $(".bar ~ li")Get all sibling element nodes after the element with class name bar<li>
2.2.3 Basic filter selector

Basic filtering selector, which means filtering the obtained elements, such as elements in even rows, etc.

Selector Function description Example
:first Get the first element in the specified selector $("li :first")Get the 1st <li>element
:last Get the last element in the specified selector $("li :last")Get the last <li>element
:even Get the odd-numbered rows of data in the specified selector with an even-numbered index. The index starts from 0 by default. $("li :even")<li>Get the odd-numbered row data with even indexes among all li elements, such as the 1st, 3rd, and 5th elements with indexes 0, 2, and 4
:odd Get the even-numbered row data in the specified selector with an odd-numbered index. The index starts from 0 by default. $("li :odd")Get the even row data with odd index among all <li>elements, such as the 2nd, 4th and 6th <li>elements with index 1,3,5
:eq(index) Get the element with index equal to index, starting from 0 by default $("li:eq(3)")<li>Get the element with index 3
:gt(index) Get elements with index greater than index $("li:gt(3)")<li>Get all elements with index greater than 3
:lt(index) Get elements with index less than index $("li:lt(3)")<li>Get all elements with index less than 3
:not(seletor) Get elements other than the specified selector $("li:not(li:eq(3))")<li>Get all elements except index 3
:focus Matches the currently focused element $("input:focus")Matches the currently focused <input>element
:animated Matches all elements that are performing animation effects $("div:not(:animated)")<div>Matches elements that are not currently animated
:target Selects the target element represented by the formatted identifier of the document URI If the URI is ,http://example.com/#foo the element will be retrieved$("div:target")<div id="foo">
2.2.4 Content Selector

Complete the acquisition of the specified element based on the content of the element. For example, get all elements whose content is not empty <li>, etc.

Selector Function description Example
:contains(text) Get the element whose content contains text $("li:contains('js')")<li>Get elements containing "js" in their content
:empty Get elements with empty content $("li:empty")<li>Get elements with empty content
:has(selector) Get the element whose content contains the specified selector $("li:has('a')")Get <a>all <li>elements containing element in content
:parent Get elements whose content is not empty (special) $("li:parent")<li>Get elements whose content is not empty
2.2.5 Visibility selector

To facilitate development, jQuery also provides access to visible or hidden elements.

Selector Function description Example
:hidden Get all hidden elements $("li:hidden")Get all hidden <li>elements
:visible Get all visible elements $("li:visible")Get all visible <li>elements
  • When the display of the specified element is set to none, the hidden element can be obtained through ":hidden".
  • When the display of the specified element is set to block, you can get the visible elements through ":visible".
2.2.6 Attribute selector

A way to get a specified element based on its attributes. For example, get <div>the element whose class value is current, etc.

Selector Function description Example
[attr] Get the element with the specified attribute $("div[class]")<div>Get all elements with class attribute
[attr=value] Get the element whose attribute value is equal to value $("div[class=current]")Get all <div>elements whose class is equal to current
[attr!=value] Get elements whose attribute value is not equal to value $("div[class!=current]")获取class不等于current的所有<div>元素
[attr^=value] 获取属性值以value开始的元素 $("div[class^=box]")获取class属性值以box开始的所有<div>元素
[attr$=value] 获取属性值以value结尾的元素 $("div[class$=er]")获取class属性值以er结尾的所有<div>元素
[attr*=value] 获取属性值包含value的元素 $("div[class*='-']")获取class属性值中含有“-”符号的所有<div>元素
[attr~=value] 获取元素的属性值包含一个value,以空格分隔 $("div[class~='box']")获取class属性值等于“box”或通过空格分隔并含有box的<div>元素,如“t box”
[attr1][attr2]...[attrN] 获取同时拥有多个属性的元素 $("input[id][name$='usr']")获取同时含有id属性和属性值以usr结尾的name属性的<input>元素
2.2.7 子元素选择器
选择器 功能描述
:nth-child(index/even/odd/公式) 索引index默认从1开始,匹配指定index索引、偶数、奇数、或符合指定公式(如2n,n默认从0开始)的子元素
:first-child 获取第一个子元素
:last-child 获取最后一个子元素
:only-child 如果当前元素是唯一的子元素,则匹配
:nth-last-child(index/even/odd/公式) 选择所有它们父元素的第n个子元素。计数从最后一个元素开始到第一个
:nth-of-type(index/even/odd/公式)) 选择同属于一个父元素之下,并且标签名相同的子元素中的第n个子元素
:first-of-type 选择所有相同的元素名称的第一个子元素
:last-of-type 选择所有相同的元素名称的最后一个子元素
:only-of-type 选择所有没有兄弟元素,且具有相同的元素名称的元素
:nth-last-of-type(index/even/odd/公式) 选择所有它们的父级元素的第n个子元素,计数从最后一个元素到第一个

带有“of-type” 与未带有“of-type”项的选择器有一定的区别。

2.2.8 表单选择器
选择器 功能描述
:input 获取页面中的所有表单元素,包含<select>以及<textarea>元素
:text 选取页面中的所有文本框
:password 选取所有的密码框
:radio 选取所有的单选按钮
:checkbox 选取所有的复选框
:submit 获取submit提交按钮
:reset 获取reset重置按钮
:image 获取type="image"的图像域
:button 获取button按钮,包括<button></button>type="button"
:file 获取type="file"的文件域
:hidden 获取隐藏表单项
:enabled 获取所有可用表单元素
:disabled 获取所有不可用表单元素
:checked 获取所有选中的表单元素,主要针对radio和checkbox
:selected 获取所有选中的表单元素,主要针对select

选择器$("input")$(":input")虽然都可以获取表单项,但是它们表达的含义有一定的区别,前者仅能获取表单标签是<input>的控件,后者则可以同时获取页面中所有的表单控件,包括表单标签是<select>以及<textarea>的控件。

2.3 元素遍历

在操作HTML文档中的DOM元素时,经常需要进行元素遍历。

jQuery提供的方法:each()

<ul>
    <li>PHP</li><li>iOS</li>
    <li>Java</li><li>UI</li>
</ul>
<script src="jquery-1.12.4.min.js"></script>
<script>
    $('li').each(function(index, element) {
      
      
        console.log('第' + (index + 1) + '个:' + $(element).text());
    });
</script>

提示:在回调函数内部还可以直接使用$(this)来表示当前元素。

2.4 元素内容

元素内容的操作有两种:获取和设置。

语法 说明
html() 获取第一个匹配元素的HTML内容
html(content) 设置第一个匹配元素的HTML内容
text() 获取所有匹配元素包含的文本内容组合起来的文本
text(content) 设置所有匹配元素的文本内容
val() 获取表单元素的value值
val(value) 设置表单元素的value值
<div class="desc">
    <font color="red"><b>Smiles to the rocky</b></font>
    <ul>
        <li>天生我材必有用,千金散尽还复来。</li>
        <li>行到水穷处,坐看云起时。</li>
    </ul>
</div>
<script src="jquery-1.12.4.min.js"></script>
<script>
    var desc = $('.desc');     // 获取class为desc的元素
    var html = desc.html();    // 获取desc的HTML内容(含有标签)
    var text = desc.text();    // 获取desc的文本内容
    console.log(html);
    console.log(text);
</script>

val()方法还可以操作表单(select、radio和checkbox)的选中情况,当要获取的元素是<select>元素时,返回结果是一个包含所选值的数组;当要为表单元素设置选中情况时,可以传递数组参数。

2.5 元素样式

元素样式操作是指获取或设置元素的style属性。

在jQuery中,可以很方便的设置元素的样式、位置、尺寸等属性。

例如,通过css()方法可以设置背景色。

语法 说明
css(name) 获取第一个匹配元素的样式
css(properties) 将一个键值对形式的对象设置为所有匹配元素的样式
css(name, value) 为所有匹配的元素设置样式
width() 获取第一个匹配元素的当前宽度值(返回数值型结果)
width(value) 为所有匹配的元素设置宽度样式(可以是字符串或数字)
height() 获取第一个匹配元素的当前高度值(返回数值型结果)
height(value) 为所有匹配的元素设置高度样式(可以是字符串或数字)
offset() 获取元素的位置,返回的是一个对象,包含left和top属性
offset(properties) 利用对象设置元素的位置,必须包含left和top属性

css()方法中传递的参数若是对象,则需要去掉CSS属性中的“-”,将第2个单词的首字母变为大写。

<div style="width:100px; height:100px; background-color: red"></div>
<script src="jquery-1.12.4.min.js"></script>
<script>
    var ele = $('div');
    var w = ele.css('width');
    var h = ele.css('height');
    ele.css({
      
      border: '2px solid black', backgroundColor: '#ccc'});
    console.log('div元素的宽:' + w + ',高:' + h);
</script>

2.6 元素筛选

jQuery提供的元素过滤和查找方法可提供元素个性化的处理,增强对文档的控制能力。

查找方法:

语法 说明
find(expr) 搜索所有与指定表达式匹配的元素
parents([expr]) 取得一个包含所有匹配元素的祖先元素的元素集合(不包含根元素)
parent([expr]) 取得一个包含所有匹配元素的唯一父元素的元素集合
siblings([expr]) 获取所有同级元素(不分上下)
next([expr]) 匹配紧邻的同级的下一个元素
prev([expr]) 匹配紧邻的同级的上一个元素

过滤方法:

语法 说明
eq(index) 获取第N个元素
filter(expr|obj|ele|fn) 使用选择器、对象、元素或函数完成指定元素的筛选
hasClass(class) 检查当前的元素是否含有某个特定的类,如果有,则返回true
is(expr) 用一个表达式来检查当前选择的元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true
has(expr) 保留包含特定后代的元素,去掉那些不含有指定后代的元素
<div>
    <ul><li>Spring</li><li>summer</li></ul>
    <ul><li>autumn</li><li>winter</li></ul>
</div>
<script src="jquery-1.12.4.min.js"></script>
<script>
    // 获取div下的所有ul
    $uls = $('div').find('ul');
    // 为下标为1的ul设置背景色
    $uls.eq(1).css('background-color', '#ccc');
</script>	

2.7 元素属性

基本属性的操作有三种:获取、设置和删除。

语法 说明
attr(name) 取得第一个匹配元素的属性值,否则返回undefined
attr(properties) 将一个键值对形式的对象设置为所有匹配元素的属性
attr(name, value) 为所有匹配的元素设置一个属性值
attr(name, function) 将函数的返回值作为所有匹配的元素的name属性值
prop(name) 取得第一个匹配元素的属性值,否则返回undefined
prop(properties) 将一个键值对形式的对象设置为所有匹配元素的属性
prop(name, value) 为所有匹配的元素设置一个属性值
prop(name, function) 将函数的返回值作为所有匹配的元素的name属性值
removeAttr(name) 从每一个匹配的元素中删除一个属性
  • attr()prop()方法只能获取第一个匹配元素的属性值。

  • 要获取所有匹配元素的属性值,则需要配合jQuery提供的each()方法进行元素遍历。

在获取或设置属性时,建议操作元素的状态,如checked、selected或disabled时使用prop()方法,其他的情况使用attr()方法。

虽然attr()方法可完成基本的属性操作,但是对于class属性的操作却不够灵活。

因此,为了方便操作,jQuery专门提供了针对class属性操作的方法。

语法 作用 说明
addClass(class) 追加样式 为每个匹配的元素追加指定的类名
removeClass(class) 移除样式 从所有匹配的元素中删除全部或者指定的类
toggleClass(class) 切换样式 判断指定类是否存在,存在则删除,不存在则添加
hasClass(class) 判断样式 判断元素是否具有class样式
  • addClass()removeClass()方法经常一起使用来切换元素的样式。
  • 若要为匹配到的元素添加和移除多个样式类名,则样式类名之间可使用空格进行分隔。

2.8 练习作业

  • 折叠菜单

    • 编写网页,设置CSS完成折叠菜单的结构和样式设置。
    • 通过层级选择器、基本过滤选择器以及查找的方法获取指定的元素对象。
    • 通过css()方法设置需要折叠以及需要展开的菜单的display值。

3 DOM节点操作

3.1 节点追加

节点追加指的是在现有的节点树中,进行父子或兄弟节点的追加。

语法 作用 说明
父子节点 append(content) 把content内容追加到匹配的元素内容尾部
父子节点 prepend(content) 把content内容追加到匹配的元素内容头部
父子节点 appendTo(content) 把匹配到的内容插入到content内容的尾部
父子节点 prependTo(content) 把匹配到的内容插入到content内容的头部
兄弟节点 after(content) 把content内容插入到元素的尾部
兄弟节点 before(content) 把content内容插入到元素的头部
兄弟节点 insertAfter(content) 把所有匹配的内容插入到content元素的尾部
兄弟节点 insertBefore(content) 把所有匹配的内容插入到content元素的头部
  • 父子节点添加指的是在匹配到的元素内部添加指定的content内容。
  • 兄弟节点指的是在匹配到的元素外部添加指定的content内容。

3.2 节点替换

节点替换是指将选中的节点替换为指定的节点。

语法 说明
replaceWith(content) 将所有匹配的元素替换成指定的HTML或DOM元素
replaceAll(selector) 用匹配的元素替换掉所有selector匹配到的元素

replaceWith()方法的参数是一个函数时,它的返回值类型必须是字符串类型,用于完成指定元素的替换操作。

3.3 节点删除

语法 说明
empty() 清空元素的内容,但不删除元素本身
remove([expr]) 清空元素的内容,并删除元素本身(可选参数expr用于筛选元素)
detach([expr]) 从DOM中删除所有匹配的元素(保留所有绑定的事件、附加的数据等)
  • empty()方法仅能删除匹配元素的文本内容,而元素节点依然存在。
  • remove()方法则可以同时删除匹配元素本身和文本内容。

3.4 节点复制

语法 说明
clone([false]) 复制匹配的元素并且选中这些复制的副本,默认参数为false
clone(true) 参数设置为true时,复制元素的所有事件处理

开发中若在复制元素节点时,想要同时复制该节点的所有事件的处理,则可以将clone()方法的操作设置为true,否则节点复制时使用默认操作false即可。

3.5 练习作业

  • 左移与右移

    • 编写网页,设置CSS完成左移右移的结构和样式设置。
    • 通过层级选择器和表单选择器获取选中的操作项。
    • 通过append()方法将匹配到的内容追加到指定元素的尾部。

4 事件操作

4.1 常用事件

标签中通过属性设置事件,每个属性都由一个on和事件名组成。例如,点击事件对应的属性为onclick。

在jQuery中则可直接使用其提供的与事件类型同名的方法。例如,点击事件对应的方法为click()

这些事件方法允许重复绑定处理程序,按照绑定顺序依次执行。

若省略参数,则表示触发事件。

分类 方法 说明
表单事件 blur([[data],function]) 当元素失去焦点时触发
表单事件 focus([[data],function]) 当元素获得焦点时触发
表单事件 change([[data],function]) 当元素的值发生改变时触发
表单事件 focusin([data],function) 在父元素上检测子元素获取焦点的情况
表单事件 focusout([data],function) 在父元素上检测子元素失去焦点的情况
表单事件 select([[data],function]) 当文本框(包括<input><textarea>)中的文本被选中时触发
表单事件 submit([[data],function]) 当表单提交时触发
键盘事件 keydown([[data],function]) 键盘按键被按下时触发
键盘事件 keypress([[data],function]) 键盘按键(Shift等非字符键除外)被按下时触发
键盘事件 keyup( [[data],function ]) 键盘按键被松开时触发
鼠标事件 mouseover([[data],function]) 当鼠标移入对象时触发
鼠标事件 mouseout([[data],function]) 在鼠标从元素上离开时触发
鼠标事件 click([[data],function]) 当单击元素时触发
鼠标事件 dblclick([[data],function]) 当双击元素时触发
鼠标事件 mousedown([[data], function]) 当鼠标指针移动到元素上方,并按下鼠标按键时触发
鼠标事件 mouseup([[data], function]) 当在元素上放松鼠标按钮时,会被触发
浏览器事件 scroll([[data],function]) 当滚动条发生变化时触发
浏览器事件 resize([[data], function]) 当调整浏览器窗口的大小时会被触发
  • 参数function表示触发事件时执行的处理程序(函数)。

  • 参数data用于为事件处理函数传递数据。(可在事件处理函数中使用“事件对象.data”获取)

$('input[type=text]').focus(function() {
    
     // 文本框获取焦点
    var tips = $('<span></span>');
    tips.html('请按要求输入');
    $('input:focus').after(tips);
});
$('input[type=text]').blur(function() {
    
      // 文本框失去焦点
    $(this).next().remove();
});
// div块的移动
// 事件对象.which:获取当前按下键盘的对应码值keyCode
// 通过offset()获取当前按下键盘时div元素的位置(left和top值)
// 根据码值修改div元素位置( left和top值)
// 提示:37(左)、38(上)、39(右)、40(下)
$(document).keydown(function(event) {
    
    
    var opt = event.which;            // 获取当前按下键盘的对应码值keyCode
    var item = $('.boxes');           // 获取操作的元素
    var left = item.offset().left;    // 获取元素距离文档左侧的位置,单位像素
    var top = item.offset().top;      // 获取元素距离文档上面的位置,单位像素
    switch(opt) {
    
    
        case 37: item.offset({
    
    left: left - 1, top: top}); break;    // 左
        case 38: item.offset({
    
    left: left, top: top - 1}); break;    // 上
        case 39: item.offset({
    
    left: left + 1, top: top}); break;    // 右
        case 40: item.offset({
    
    left: left, top: top + 1}); break;    // 下
    }
});
// 鼠标移入
$('.hit').mouseover(function() {
    
    
    $(this).css('background-color', 'green');
});
// 鼠标移出
$('.hit').mouseout(function() {
    
    
    $(this).css('background-color', '');
});

4.2 页面加载事件

类比选项 window.onload $(document).ready()
执行时机 必须等待网页中的所有内容加载完成后(包括外部元素,如图片)才能执行 网页中的所有DOM结构绘制完成后就执行(可能关联内容并未加载完成)
编写个数 不能同时编写多个 能够同时编写多个
简化写法 $()

jQuery中的ready与JavaScript中的onload相比,不仅可以在页面加载后立即执行,还允许注册多个事件处理程序。

// jQuery中的页面加载事件方法有3种语法形式,具体如下。
$(document).ready(function() {
    
      });  // 语法方式1
$().ready(function() {
    
      });		     // 语法方式2
$(function() {
    
      });			         // 语法方式3

4.3 事件绑定与切换

事件处理机制,即事件绑定和事件切换,统一了事件处理的各种方法。

语法 说明
on(events,[selector],[data],function) 在匹配元素上绑定一个或多个事件处理函数
off(events,[selector],[function]) 在匹配元素上移除一个或多个事件处理函数
one(events,[data],function) 为每个匹配元素的事件绑定一次性的处理函数
trigger(type,[data]) 在每个匹配元素上触发某类事件
triggerHandler(type,[data]) 同trigger(),但浏览器默认动作将不会被触发
hover([over,]out) 元素鼠标移入与移出事件切换
  • 参数events表示事件名(多个用空格分隔)。
  • 参数selector表示选择器。
  • 参数data表示将要传递给事件处理函数function的数据。
  • 参数type表示为元素添加的事件类型(多个用空格分隔)。
  • 参数over和out分别表示鼠标移入移出时的事件处理函数。
// 事件的绑定
$('div').on('click', function() {
    
    
    console.log('已完成单点击');
});
// 事件的取消
$('div').off('click');
// 绑定单次事件
$('div').one('click', function() {
    
    
    console.log('已完成1次单点击');
});
// 多个事件绑定同一个函数
$('div').on('mouseover mouseout', function() {
    
    
    console.log('鼠标移入或移出');
});
// 多个事件绑定不同的函数
$('div').on({
    
    
    mouseover: function() {
    
    
        console.log('鼠标移入');
    },
    mouseout: function() {
    
    
        console.log('鼠标移出');
    }
});
// 为以后创建的元素委派事件
$('body').on('click', 'div', function() {
    
    
    console.log('收到');
});
//测试:创建<div>元素
$('body').append('<div>测试</div>');
// 鼠标移入移出事件切换
$('div').hover(function() {
    
    
    console.log('鼠标移入')
}, function() {
    
    
    console.log('鼠标移出');
});

on()方法与off()方法是jQuery从1.7版本开始新增的方法。jQuery官方推荐使用on()方法进行事件绑定,在新版本中已经取代了bind()delegate()live()方法。

4.4 练习作业

  • 手风琴效果
    • 编写网页,设置CSS完成手风琴的结构和样式设置。
    • 为所有图片添加鼠标移入与移出事件。
    • 鼠标移入时,将当前元素的width设为图片的原宽,其他图片的width= (<div>的宽度 - 图片的原宽) / 剩余图片元素个数
    • 鼠标移出时,所有图片的width=<div>的宽度 / 所有图片的个数

5 动画特效

5.1 常用动画

分类 方法 说明
基本特效 show([speed,[easing],[fn]]) 显示隐藏的匹配元素
基本特效 hide([speed,[easing],[fn]]) 隐藏显示的匹配元素
基本特效 toggle([speed],[easing],[ fn]) 元素显示与隐藏切换
滑动特效 slideDown([speed],[easing],[ fn]) 垂直滑动显示匹配元素(向下增大)
滑动特效 slideUp([speed,[easing],[ fn]]) 垂直滑动显示匹配元素(向上减小)
滑动特效 slideToggle([speed],[easing],[ fn]) 在slideUp()和slideDown()两种效果间的切换
淡入淡出 fadeIn([speed],[easing],[ fn]) 淡入显示匹配元素
淡入淡出 fadeOut([speed],[easing],[ fn]) 淡出隐藏匹配元素
淡入淡出 fadeTo([[speed],opacity,[easing],[ fn]]) 以淡入淡出方式将匹配元素调整到指定的透明度
淡入淡出 fadeToggle([speed,[easing],[ fn]]) 在fadeIn()和fadeOut()两种效果间的切换
  • 参数speed表示动画的速度,可设置为动画时长的毫秒值(如1000),或预定的3种速度(slow、fast和normal)。
  • 参数easing表示切换效果,默认效果为swing,还可以使用linear效果。
  • 参数fn表示在动画完成时执行的函数。
  • 参数opacity表示透明度数值(范围在0~1之间,0代表完全透明,0.5表示50%透明,1代表完全不透明)。

5.2 自定义动画

方法 说明
animate(params [,speed] [,easing] [,fn]) 用于创建自定义动画的函数
$.speed([speed] [,settings]) 创建一个包含一组属性的对象用来定义自定义动画
queue([queueName]) 显示被选元素上要执行的函数队列
delay(speed [,queueName]) 设置一个延时来推迟执行队列中之后的项目
clearQueue([queueName]) 从尚未运行的队列中移除所有项目
dequeue([queueName]) 从队列移除下一个函数,然后执行函数
finish([queueName]) 停止当前正在运行的动画,删除所有排队的动画,并完成匹配元素所有的动画
stop([clearQueue] [, jumpToEnd]) 停止所有在指定元素上正在运行的动画
  • 参数params表示一组包含动画最终属性值的集合。
  • 参数settings是easing与fn组成的一个对象集合。
  • 参数queueName表示队列名称,默认值为fx(标准效果队列)。
  • 参数clearQueue与jumpToEnd都是布尔类型,默认值为false,前者规定是否停止被选元素所有加入队列的动画,后者规定是否立即完成当前的动画。
<input id="btn" type="submit" value="开始动画"><div></div>
<script>	
    $('#btn').click(function () {
      
      
        $('div').css({
      
      background: 'red', width: 0, height: 0});
        var params = {
      
      width: '100px', height: '100px'};
        var settings = $.speed(2000, 'linear');
        $('div').animate(params, settings);
    });
</script>
// 动画队列
$('div').show('slow')
    .animate({
    
    left: '+=200'}, 2000)
    .animate({
    
    left: '-=200'}, 1500)
    .slideUp('normal', runQue);
// 队列长度
$('div').queue('fx').length;
div.show('slow')
    .animate({
    
    left: '+=200'}, 2000)
    .queue(function() {
    
    
    // 为队列添加额外操作
    $(this).css('background', 'green').dequeue();
})
    .animate({
    
    left: '-=200'}, 1500)
    .slideUp('normal', runQue)
    .queue(function() {
    
    
    // 为队列添加额外操作
    $(this).css('background', 'red').dequeue();
});

5.3 练习作业

  • 无缝轮播图
    • 焦点图的各个图片(即需要轮播的图片)依次横向排列。
    • 设置焦点图的外边框的宽度以及超出隐藏,限定其只能显示一张图片。
    • 切换到下一张时,只需要修改焦点图外层样式中的left值,就可以将焦点图整体向左移动,从而显示第2张图片。
    • 当焦点图显示到最后一张图片时,再向左切换就会回到第一张图片,这就是无缝切换效果。
    • 为了实现这种效果,将第一张图片连接到最后一张图片的后面,然后等这张图片向左移动直到完全显示之后,立即将焦点图的left值设为0,就切换到第1张图片了。

6 jQuery操作Ajax

传统的Ajax是通过XMLHttpRequest实现的,不仅代码复杂,而且浏览器兼容问题也比较多。

jQuery中通过对Ajax操作的封装,极大地简化了Ajax操作的开发过程。

分类 方法 说明
高级应用 $.get(url[,data][,fn][,type]) 通过远程HTTP GET请求载入信息
高级应用 $.post(url[,data][,fn][, type]) 通过远程HTTP POST请求载入信息
高级应用 $.getJSON(url[,data][,fn]) 通过HTTP GET请求载入JSON数据
高级应用 $.getScript(url[,fn]) 通过HTTP GET请求载入并执行一个JavaScript文件
高级应用 元素对象.load(url[,data] [,fn]) 载入远程HTML文件代码并插入至DOM中
底层应用 $.ajax(url[,options]) 通过HTTP请求加载远程数据
底层应用 $.ajaxSetup(options) 设置全局Ajax默认选项
  • 参数url表示待请求页面的URL地址。
  • data表示传递的参数。
  • 参数fn表示请求成功时,执行的回调函数。
  • 参数type用于设置服务器返回的数据类型,如XML、JSON、HTML、TEXT等。
  • 参数options用于设置Ajax请求的相关选项。
选项名称 说明
url 处理Ajax请求的服务器地址
data 发送Ajax请求时传递的参数,字符串类型
success Ajax请求成功时所触发的回调函数
type 发送的HTTP请求方式,如get、post
datatype 期待的返回值类型,如xml、json、script或html数据类型
async 是否异步,true表示异步,false表示同步,默认值为true
cache 是否缓存,true表示缓存,false表示不缓存,默认值为true
contentType 请求头,默认值为application/x-www-form-urlencoded; charset=UTF-8
complete 当服务器URL接收完Ajax请求传送的数据后触发的回调函数
jsonp 在一个jsonp请求中重写回调函数的名称
$.post('index.php', {
    
    'id': 2, 'name': 'JS'}, function(msg) {
    
    
    console.log(msg.id + '-' + msg.name);    // 输出结果:2-JS
}, 'json');

上述代码表示处理当前Ajax请求的地址是同级目录下的index.php,在Ajax请求成功后,接收index.php返回的JSON格式的数据并在控制台进行输出。

  • 在jQuery中对Ajax的操作方法中,$.ajax(url,[options])是底层方法。

  • 通过该方法的options参数,可以实现$.get()$.post() ‘ . g e t J S O N ( ) ‘ 和 ‘ `.getJSON()`和` ‘.getJSON().getScript()`方法同样的功能。

  • 下面列举$.ajax()方法的3种常用方式。

    • 只发送GET请求

      $.ajax('index.php');
      
    • 只配置setting参数,同样实现Ajax操作

      $.ajax('index.php',{
              
              
          data: {
              
              'book': 'PHP', 'sales': 2000},  // 要发送的数据
          success:function(msg){
              
              // 请求成功后执行的函数
              alert(msg);
          }
      });
      
    • 发送GET请求并传递数据,接收返回结果

      $.ajax({
              
              
          type: 'GET
          url: 'index.php',
          data: {
              
              'id': 2, 'name': 'JS'},
          success: function(msg) {
              
              
              console.log(msg);
          }
      });
      
      $.ajaxSetup({
              
              
          type: 'GET',
          url: 'index.php',
          data:{
              
              'id': 2, 'name': 'JS'},
          success: function(msg) {
              
              
              alert(msg);
          }
      });
      $.ajax();
      

除此之外,在jQuery中还为操作Ajax额外的提供了一些辅助的函数以及相关的Ajax事件处理方法,方便开发。

分类 方法/函数 说明
辅助函数 $.param(obj) 创建数组或对象的序列化表示
辅助函数 serialize() 通过序列化表单值,创建URL编码文本字符串
辅助函数 serializeArray() 通过序列化表单值,创建对象数组(名称和值)
Ajax事件 ajaxComplete(fn) Ajax请求完成时触发的事件执行函数
Ajax事件 ajaxError(fn) Ajax请求发生错误时触发的事件执行函数
Ajax事件 ajaxSend(fn) Ajax请求发送前触发的事件执行函数
Ajax事件 ajaxStart(fn) Ajax请求开始时触发的事件执行函数
Ajax事件 ajaxStop(fn) Ajax请求结束时触发的事件执行函数
Ajax事件 ajaxSuccess(fn) Ajax请求成功时触发的事件执行函数
// 序列化对象
var data = {
    
    'id': 2, 'name': 'Lucy', skill: ['PHP', 'JS']};
var seri_data = $.param(data);
var deseri_data = decodeURIComponent(seri_data);
// 输出结果:id=2&name=Lucy&skill%5B%5D=PHP&skill%5B%5D=JS
console.log(seri_data); 
// 输出结果:id=2&name=Lucy&skill[]=PHP&skill[]=JS
console.log(deseri_data);

上述代码表示处理当前Ajax请求的地址是同级目录下的index.php,在Ajax请求成功后,接收index.php返回的JSON格式的数据并在控制台进行输出。

// 序列化表单数据
$('input[type=button]').on('click', function () {
    
    
    console.log($('form').serialize());
    console.log($('form').serializeArray());
});

Ajax各个事件处理的先后顺序为ajaxStart() > ajaxSend() > ajaxSuccess()、ajaxError() > ajaxComplete() > ajaxStop()

根据Ajax请求是否发生错误在Ajax发送后执行ajaxSuccess()还是ajaxError()方法进行相关的处理。

$(document).ajaxError(function() {
    
    
    console.log('ajaxError');
});
$.post('index.php', {
    
    'id': 2, 'name': 'JS'}, function(msg) {
    
    
    console.log(msg.id + '-' + msg.name);
}, 'xml');

7 插件机制

7.1 自定义插件

  • 封装jQuery对象方法

    // 在插件中封装1个方法
    (function($){
          
          
        $.fn.方法名 = function() {
          
          
            // 实现插件的代码
            ……
        };
    })(jQuery);
    
    • . f n 是 j Q u e r y 的原型对象(相当于 .fn是jQuery的原型对象(相当于 .fnjQuery的原型对象(相当于.prototype)。
    • 通过“$.fn.方法名”的方式将封装的功能方法对每一个jQuery实例都有效,成为jQuery的插件。
    • jQuery的简写“ ”是可以被修改的,为了避免影响到插件中的代码,建议将插件方法放在“ ‘ ( f u n c t i o n ( ”是可以被修改的,为了避免影响到插件中的代码,建议将插件方法放在“`(function( 是可以被修改的,为了避免影响到插件中的代码,建议将插件方法放在“‘(function(){……})(jQuery);`”这个包装函数中,该函数的参数$就表示jQuery全局对象。
    // 在插件中封装多个方法
    jQuery.fn.extend({
          
          
        方法名1:function(参数列表) {
          
          
            // 实现插件的代码
            ……
        },
        方法名2:function(参数列表) {
          
          
            // 实现插件的代码
            ……
        }
    });
    
    • 若要在一个插件中封装多个方法,则可以借助extend()方法,为该方法传递对象类型的参数。
    • 参数的设置按照JavaScript对象语法的编写方式即可实现多个方法的封装。
    • 插件文件的名称建议遵循“jquery.插件名.js”的命名规则,防止与其他JavaScript库插件混淆。
  • 定义全局函数

    // 定义全局函数的插件
    jQuery.extend({
          
          
        方法名1: function(参数列表){
          
          
            // 实现插件的代码
            ……
        },
        方法2: function(参数列表){
          
          
            // 实现插件的代码
            ……
        }
    });
    
    • 将自定义函数附加到jQuery命名空间下,从而作为一个公共的全局函数使用。
    • 例如,jQuery的ajax()方法就是利用这种途径内部定义的全局函数。
  • 自定义选择器

    $.expr[":"].方法名称 = function(obj) {
          
          
        // 自定义选择器代码
        return 匹配HTML元素的条件;
    };
    
    • 用户可以利用jquery.expr实现选择器的自定义。
    • obj表示进行匹配的HTML元素对应的jQuery对象。
    • 根据需要对jQuery对象的属性进行判断,并使用return返回匹配结果。

7.2 jQuery插件库

随着jQuery的发展,诞生了许多优秀的插件。

网站地址为:http://plugins.jquery.com/。

通过在搜索框中输入插件名即可搜索需要的插件。

7.3 jQuery UI

  • jQuery UI是在jQuery基础上新增的一个库。
  • Features: It has powerful scalable functions, attractive and beautiful pages, and can more easily add professional-level UI elements to web pages.
  • For example: calendar, menu, drag and drop, resize and other interactive effects.
  • download link
<!-- 引入所需文件 -->
<script src="jQuery-1.12.4.min.js"></script>
<script src="jquery-ui/jquery-ui.min.js"></script>
<link rel="stylesheet" href="jquery-ui/jquery-ui.css">

<div id="datepicker"></div>

<!-- 实例化datepicker -->
<script>
    $('#datepicker').datepicker();
    
    // 自定义日历显示样式
    $('#datepicker').datepicker({
      
      
        changeMonth: true,      	// 下拉列表方式选择月份
        changeYear: true,       	// 下拉列表方式选择年
        firstDay: 1,            	// 星期显示顺序为:“Mo Tu We Th Fr Sa Su”
        showOtherMonths: true, // 当前月中空白的日期利用相邻月日期填充
    });
    
    // 自定义中文显示
    var m = ['一月', '二月', '三月', '四月', '五月', '六月','七月', '八月', '九月', '十月', '十一月', '十二月'];
    var d = ['日', '一', '二', '三', '四', '五', '六'];
    $('#datepicker').datepicker({
      
      
        ……
        monthNamesShort: m,
        dayNamesMin: d,
    });
</script>

In an actual project, if you only do Chinese development, it will be troublesome to configure these properties every time you use it. It is recommended to save the Chinese-related configuration in a JavaScript file and reference it directly every time you use it.

7.4 Practice assignments

  • Custom select all and invert selection plug-ins
    • Write a table to display data and provide "select all", "inverse select" and "unselect all" operation buttons.
    • Introduce jQuery files and customized plug-in files (to be written).
    • Write a custom plug-in file and implement the plug-in by encapsulating jQuery object methods.
    • In HTML, call the plug-in encapsulation method to realize the functions of selecting all, inverting selection, and deselecting none.

ery-ui.min.js">


> 在实际项目中若只做中文开发,则每次使用时都配置这些属性会比较麻烦,建议将中文相关的配置保存到一个JavaScript文件中,每次使用时直接引用即可。



### 7.4 练习作业

- 自定义全选与反选插件
  - 编写表格展示数据,为其提供“全选”、“反选”和“全不选”操作按钮。
  - 引入jQuery文件以及自定义的插件文件(待编写)。
  - 编写自定义插件文件,利用封装jQuery对象方法的方式实现插件。
  - 在HTML中,调用插件封装的方法,实现全选、反选以及全不选的功能。


Guess you like

Origin blog.csdn.net/zhangchen124/article/details/133383936