参考:


目录:

  • 1、引用 jQuery、Prototype

  • 2、jQuery语法
  • 3、jQuery选择器
  • 4、jQuery效果
  • 5、jQuery HTML文档操作
    • 5.1 jQuery DOM 操作
    • 5.2 获得内容和属性
      • (1)获取内容 - text()、html() 以及 val()
      • (2)获取属性 - attr()
    • 5.3 设置内容和属性
      • (1)设置内容 - text()、html() 以及 val()
      • (2)text()、html() 以及 val()的回调函数
      • (3)设置内容 - attr()
      • (4)attr() 的回调函数
    • 5.3 添加元素(添加新的 HTML 内容)
      • (1)jQuery append() 方法
      • (2)jQuery prepend() 方法
      • (3)通过 append() 和 prepend() 方法添加若干新元素
      • (4)jQuery after() 和 before() 方法
      • (5)通过 after() 和 before() 方法添加若干新元素
    • 5.6 尺寸(盒模型)

      • (1)介绍几个概念
      • (2)jQuery width() 和 height() 方法
      • (3)jQuery innerWidth() 和 innerHeight() 方法
      • (4)jQuery outerWidth() 和 outerHeight() 方法
  • 6、jQuery遍历
  • 7、事件方法
  • 8、JavaScript异步编程的四种方法
  • 9、jQuery使用技巧
    • 9.1 按钮的置灰、Loading、恢复等操作使用技巧
    • 9.2 jQuery Utilities ($. 为 jQuery)
      • (1)$.clearQueue() :从队列中删除尚未运行的所有函数

        // 举例
        $("#stop").click(function () {
        var myDiv = $("div");
        myDiv.clearQueue();
        myDiv.clearQueue();
        });

        输出结果:略。

      • (2)$.dequeue() :对队列执行匹配元素的下一个函数
      • (3)$.contains(container, contained) :检查DOM元素是否是DOM元素的后代
        $.contains(document.documentElement, document.body) // true
        $.contains(document.body, document.documentElement) // false

        输出结果:略。

      • (4)$.data(element, key, value), .data(element, key), .data(element) :存储与指定元素关联的任意数据和 / 或返回已设置的值
        $.data($("div")[0], "test-key", {
        fisrt: 16,
        last: "pizza!"
        })
        // 返回:{ fisrt: 16, last: "pizza!" }
        $.data($("div")[0], "test-key")
        // 返回:{ fisrt: 16, last: "pizza!" }
        $.data($("div")[0], "test-key").first
        // 返回:16

        输出结果:略。

      • (5)$.each() :通用迭代器函数,可用于无缝迭代对象和数组
        $.each([52, 97, 33], function (index, value) {
        console.log(index + ": " + value);
        });
        $.each({ "a": "1", "b": "2" }, function (key, value) {
        console.log(key + ": " + value);
        });

        输出结果:略。

      • (6)$.extend() :将两个或多个对象的内容合并到第一个对象中(包括按照键值去重,后面替换前面数据)
        $.extend({}, { "a": "1", "b": "2" }); // {a: "1", b: "2"}
        $.extend({}, { "a": "1", "b": "2" }, { "a": "3" }); // {a: "3", b: "2"}
        $.extend({}, { "a": "1", "b": "2" }, { "c": "3" }); // {a: "1", b: "2", "c": "3"}
        $.extend({ "a": "1" }, { "b": "2" }, { "c": "3" }); // {a: "1", b: "2", "c": "3"}

        输出结果:略。

      • (7)$.fn.extend():将对象的内容合并到jQuery原型上,以提供新的jQuery实例方法
        举例:按钮的置灰、Loading、恢复等操作使用技巧
      • (8)$.globalEval(code), $.globalEval(code):全局执行一些JavaScript代码
        function test() {
        $.globalEval("var newVar = true;")
        }
        test(); // newVar === true -> true

        输出结果:略。

      • (9)$.grep(array, funcition(item) { return xxx; }), $.grep(array, funcition(item, index) { return xxx; }):查找满足过滤函数的数组元素,原始数组不受影响
        var arr = [1, 2, 6, 4, 9, 6, 5, 0, 8];
        $.grep(arr, item => item >= 4); // [6, 4, 9, 6, 5, 8]
        $.grep(arr, (item, index) => item >= 4 && index > 3); // [9, 6, 5, 8]

        输出结果:略。

      • (10)$.inArray(value, array), $.inArray(value, array, fromIndex):在数组中搜索指定的值并返回索引(如果未找到,则返回-1)
        $.inArray(10, [1, 2, 5, 9, 4, 10, 14, 8]) //
        $.inArray(10, [1, 2, 5, 9, 4, 10, 14, 8], 0) //
        $.inArray(10, [1, 2, 5, 9, 4, 10, 14, 8], 6) // -1

        输出结果:略。

      • (11)$.isArray(obj):确定参数是否是数组
        $.isArray([]) // true
        $.isArray([1]) // true
        $.isArray({}) // false

        输出结果:略。

      • (12)$.isEmptyObject(obj):检查对象是否为空(不包括可枚举的属性)
        $.isEmptyObject({}) // true
        $.isEmptyObject({foo: "bar"}) // false

        输出结果:略。

      • (13)$.isFunction(value):检查对象是否为空(不包括可枚举的属性),已经废弃,可以用 typeof x === "function" 替换
      • (14)$.isNumeric(value):检查其参数是否表示数值。如果是,返回true,否则,返回false。参数可以是任意类型
      • (15)$.isPlainObject(obj):检查对象是否是普通对象(使用 "{}" 或者 "new Object" 创建)
      • (16)$.isWindow(obj):确定参数是否为窗口
        $.isWindow(window) // true
        $.isWindow({}) // false

        输出结果:略。

      • (17)$.isXMLDoc(node):检查DOM节点是否在XML文档中
        $.isXMLDoc(document) // false
        $.isXMLDoc(document.body) // false

        输出结果:略。

      • (18)$.makeArray(obj) :将类似数组的对象转换为真正的JavaScript数组
        $.makeArray({ "a": 1, "b": 2, "c": 3 }) // [{ "a": 1, "b": 2, "c": 3 }]

        输出结果:略。

      • (19)$.map(array, callback):将数组或者对象中的所有项目转换为新的项目数组
        $.map([1, 2, 4, 5, 3], item => item * 2) // [2, 4, 8, 10, 6]
        $.map({ "a": 1, "b": 2, "c": 3 }, item => item * 2) //?[2, 4, 6]

        输出结果:略。

      • (20)$.merge(first, second):将两个数组的内容合并到第一个数组中
        $.merge([1, 2, 3, 4, 5], [6, 7, 8, 9]) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
        $.merge([1, 2, 3, 4, 5], [5, 7, 8, 9]) // [1, 2, 3, 4, 5, 5, 7, 8, 9]

        输出结果:略。

      • (21)$.noop():一个空函数
      • (22)$.now():返回当前时间(时间戳),(new Date()).getTime() 的简写
      • (23)$.parseHTML(data), $.parseHTML(data, context), $.parseHTML(data, context, keepScript):将字符串解析为DOM节点数组
        data:要解析的HTML字符串;context:Document元素,用于创建HTML片段的上下文;keepScript:一个布尔值,指示是否包含HTML字符串中传递的脚本
        $.parseHTML("Hello, <b>my name is</b> jQuery.")[0] // "Hello, "
        $.parseHTML("Hello, <b>my name is</b> jQuery.")[1] // "<b>my name is</b>"
        $.parseHTML("Hello, <b>my name is</b> jQuery.")[2] // " jQuery."

        输出结果:略。

      • (24)$.parseJSON(json):将JSON字符串转换为标准JSON格式,不推荐使用,推荐使用 JSON.parse(json) 方法
        JSON.parse('{"a": 1, "b": 2}') // {a: 1, b: 2}
        $.parseJSON('{"a": 1, "b": 2}') // {a: 1, b: 2}

        输出结果:略。

      • (25)$.parseXML(data):将字符串解析为XML文档
        $.parseXML("<b>Hello, world</b>") // <b>Hello, world</b>

        输出结果:略。

      • (26)$.proxy(function, context), $.proxy(context, name), $.proxy(function, context, additionalArguments):获取一个函数并返回一个始终具有特定上下文的心函数
        context:PlainObject, additionalArguments: Anything

      • (27)$.queue(element, queueName), $.queue(element, queueName, newQueue), $.queue(element, queueName, callback):显示或操作要在匹配元素上执行的函数队列
      • (28)$.removeData(element), $.removwData(element, name):删除之前存储的数据

        $.data($("div")[0], "test-key", {
        fisrt: 16,
        last: "pizza!"
        })
        $.data($("div")[0], "test-key") // { fisrt: 16, last: "pizza!" }
        $.data($("div")[0], "test-key").first //
        $.removeData($("div")[0], "test-key")
        $.data($("div")[0], "test-key") // undefined

        输出结果:略。

      • (29)$.support:表示在不同浏览器功能或错误的属性集合。用于jQuery内部使用,当内部不再需要特定属性以提高页面启动性能时,可以删除这些属性。对于自己的项目的功能检测需求,建议使用如 Modernizr 之类的外部库,而不是依赖于属性 jQuery.support
      • (30)$.trim(str):删除字符串开头和结尾的空白。
        $.trim("  Hello") // "Hello"
        $.trim(" Hello ") // "Hello"

        输出结果:略。

      • (31)$.type(obj):确定内部JavaScript的[Class]
        $.type("Hello") // "string"
        $.type("new Date") // "date"
        // ...

        输出结果:略。

      • (32)$.unique(array):对一组DOM元素进行排序。这仅使用于DOM元素的数组,而不适用于字符串或数字
      • (33)$.uniqueSort(array):对一组DOM元素进行排序,删除重复项。这仅使用于DOM元素的数组,而不适用于字符串或数字

  jQuery 是一个 JavaScript 库。jQuery 极大地简化了 JavaScript 编程。

1、引用 jQuery、Prototype

1.1 引用jQuery

  如需测试 JavaScript 库,您需要在网页中引用它。

  为了引用某个库,请使用 <script> 标签,其 src 属性设置为库的 URL:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title>
<!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js">
</script>
</head> <body> </body>
</html>

1.2 引用Prototype

  如需测试 JavaScript 库,您需要在网页中引用它。

  为了引用某个库,请使用 <script> 标签,其 src 属性设置为库的 URL:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title>
<!--引用Prototype库,src可以直接指向本地下载的Prototype库-->
<!--<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js">-->
<script src="prototype.js">
</script>
</head> <body> </body>
</html>

1.3 jQuery描述

  jQuery 是一个“写的更少,但做的更多”的轻量级 JavaScript 库。

  主要的 jQuery 函数是 $() 函数(jQuery 函数)。如果您向该函数传递 DOM(Document Object Model) 对象,它会返回 jQuery 对象,带有向其添加的 jQuery 功能。

  jQuery 允许您通过 CSS 选择器来选取元素。

  在 JavaScript 中,您可以分配一个函数以处理窗口加载事件:

  JavaScript 方式:

 function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello jQuery";
}
onload=myFunction;

  举例如下:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title>
</head> <body onload="myFunction()"> <h1 id="h01">Hello, world!</h1> <script>
function myFunction() {
var id = document.getElementById("h01");
id.innerHTML = "Hello, jQuery!";
}
</script>
</body>
</html>

  输出结果:Hello, jQuery!

  等价的 jQuery 是不同的:

  jQuery 方式:

 function myFunction()
{
$("#h01").html("Hello jQuery");
}
$(document).ready(myFunction);

  上面代码的最后一行,HTML DOM 文档对象被传递到 jQuery :$(document)。

  当您向 jQuery 传递 DOM 对象时,jQuery 会返回以 HTML DOM 对象包装的 jQuery 对象。

  jQuery 函数会返回新的 jQuery 对象,其中的 ready() 是一个方法。

  由于在 JavaScript 中函数就是变量,因此可以把 myFunction 作为变量传递给 jQuery 的 ready 方法。

  提示:jQuery 返回 jQuery 对象,与已传递的 DOM 对象不同。jQuery 对象拥有的属性和方法,与 DOM 对象的不同。您不能在 jQuery 对象上使用 HTML DOM 的属性和方法。

  举例1:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title>
<!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js">
</script>
</head> <body> <h1 id="h01"></h1> <script>
function myFunction() {
$("#h01").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</body>
</html>

  输出结果:Hello, jQuery!

  举例2:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title>
<!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js">
</script>
</head> <body> <h1 id="h01"></h1> <script>
function myFunction() {
$("#h01").attr("style", "color:red").html("Hello, jQery!");
}
$(document).ready(myFunction);
</script>
</body>
</html>

  输出结果:Hello, jQery!

  举例3:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p").click(function() {
$(this).hide();
});
});
</script>
</head> <body> <p>如果您点击我,我会消失。</p>
<p>点击我,我会消失。</p>
<p>也要点击我哦。</p> </body>
</html>

  输出结果:略。

1.4 Prototype描述

  Prototype 提供的函数可使 HTML DOM 编程更容易。

  与 jQuery 类似,Prototype 也有自己的 $() 函数。

  $() 函数接受 HTML DOM 元素的 id 值(或 DOM 元素),并会向 DOM 对象添加新的功能。

  与 jQuery 不同,Prototype 没有用以取代 window.onload() 的 ready() 方法。相反,Prototype 会向浏览器及 HTML DOM 添加扩展。

  在 JavaScript 中,您可以分配一个函数以处理窗口加载事件:

 function myFunction()
{
$("h01").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);

  Event.observe() 接受三个参数:

  • 您希望处理的 HTML DOM 或 BOM(浏览器对象模型)对象
  • 您希望处理的事件
  • 您希望调用的函数

  举例1:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title>
<!--引用Prototype库,src可以直接指向本地下载的Prototype库-->
<!--<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js">-->
<script src="prototype.js">
</script>
</head> <body>
<h1 id="h01"></h1> <script>
function myFunction() {
$("h01").insert("Hello Prototype!");
}
Event.observe(window, "load", myFunction);
</script>
</body>
</html>

  输出结果:Hello, jQuery!

  举例2:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title>
<!--引用Prototype库,src可以直接指向本地下载的Prototype库-->
<!--<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js">-->
<script src="prototype.js">
</script>
</head> <body>
<h1 id="h01"></h1> <script>
function myFunction() {
$("h01").writeAttribute("style", "color:red").insert("Hello Prototype!");
}
Event.observe(window, "load", myFunction);
</script>
</body>
</html>

  输出结果:Hello, jQery!

  正如您在上面的例子中看到的,与 jQuery 相同,Prototype 允许链式语法。

  链接(Chaining)是一种在同一对象上执行多个任务的便捷方法。

2、jQuery 语法

  通过 jQuery,您可以选取(查询,query) HTML 元素,并对它们执行“操作”(actions)。

2.1 jQuery语法举例

  • (1)$(this).hide()
  • (2)$("#id_test").hide()
  • (3)$("p").hide()
  • (4)$(".class_test").hide()

(1)$(this).hide()

  演示 jQuery hide() 函数,隐藏当前的 HTML 元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$(this).hide();
});
});
</script>
</head> <body> <button type="button">Click me</button> </body>
</html>

  输出结果:出现 “Click me” 按钮,点击即消失。

(2)$("#id_test").hide()

  演示 jQuery hide() 函数,隐藏 id="id_test" 的元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("#p1_test").hide();
});
});
</script>
</head> <body> <h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="p1_test">This is another paragraph.</p>
<button type="button">Click me</button> </body>
</html>

  输出结果:点击按钮,“This is another paragraph.”会消失。

(3)$("p").hide()

  演示 jQuery hide() 函数,隐藏所有 <p> 元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("p").hide();
});
});
</script>
</head> <body> <h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button> </body>
</html>

  输出结果:点击按钮后,“This is a paragraph.”和“This is another paragraph.”都会消失。

(4)$(".class_test").hide()

  演示 jQuery hide() 函数,隐藏所有 class="class_test" 的元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$(".p1_class").hide();
});
});
</script>
</head> <body> <h2>This is a heading</h2>
<p class="p1_class">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button> </body>
</html>

  输出结果:点击按钮后,“This is a paragraph.”会消失。

2.2 jQuery 语法

  jQuery 语法是为 HTML 元素的选取编制的,可以对元素执行某些操作。

  基础语法是:$(selector).action()

  • 美元符号定义 jQuery
  • 选择符(selector)“查询”和“查找” HTML 元素
  • jQuery 的 action() 执行对元素的操作

2.3 文档就绪函数

  您也许已经注意到在我们的实例中的所有 jQuery 函数位于一个 document ready 函数中:

$(document).ready(function() {
<!--jQuery functions go here-->
});

  这是为了防止文档在完全加载(就绪)之前运行 jQuery 代码。

  如果在文档没有完全加载之前就运行函数,操作可能失败。下面是两个具体的例子:

  • 试图隐藏一个不存在的元素
  • 获得未完全加载的图像的大小

3、jQuery选择器

  在前面的章节中,我们展示了一些有关如何选取 HTML 元素的实例。

  关键点是学习 jQuery 选择器是如何准确地选取您希望应用效果的元素。

  jQuery 元素选择器和属性选择器允许您通过标签名、属性名或内容对 HTML 元素进行选择。

  选择器允许您对 HTML 元素组或单个元素进行操作。

  在 HTML DOM 术语中:

  选择器允许您对 DOM 元素组或单个 DOM 节点进行操作。

在浏览器 Elements 中唯一选择一个元素标识:

在浏览器中,获取元素下面的一个子元素:

  举例:查询"#id1"元素下面的"#id2"下面的"#id3"元素("#id2"和"#id3"之间用空格隔开)

$("#id1").find("#id2 #id3")

  输出结果:略。

3.1 jQuery元素选择器  

  jQuery 使用 CSS 选择器来选取 HTML 元素。

  1. $("p") 选取 <p> 元素。
  2. $("p.intro") 选取所有 class="intro" 的 <p> 元素。
  3. $(".intro") 选取所有 class="intro" 的所有元素。
  4. $("p#demo") 选取所有 id="demo" 的 <p> 元素。
  5. $("#demo") 选取所有 id="demo" 的所有元素

3.2 jQuery属性选择器 

  jQuery 使用 XPath 表达式来选择带有给定属性的元素。

$("[attribute='value']"

选择指定属性值等于给定字符串或者以该字符串为前缀(该字符串后跟一个连接符"-")的元素。

注意:引号是可选的,可以是一个不带引号的一个单词,或者带一个引号的字符串。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p2"></p> <script type="text/javascript">
$(document).ready(function() {
$("p[class='class_p1']").html("第一个p标签");
$("p[id='id_p2']").html("第二个p标签");
})
</script>
</body>
</html>

  输出结果:略。

$("[attribute*='value']"

选择指定属性具有包含一个给定的子字符串的元素。(选择给定的属性是以包含某些值的元素)

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p2"></p> <script type="text/javascript">
$(document).ready(function() {
$("p[class*='class_']").html("第一个p标签");
$("p[id*='_p2']").html("第二个p标签");
})
</script>
</body>
</html>

  输出结果:略。

$("[attribute~='value']"

选择指定属性用空格分割的值中包含一个给定值的元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <input name="man-news" />
<input name="milk man" /> <script type="text/javascript">
$(document).ready(function() {
$("input[name~='man']").val("mr.man is in it");
})
</script>
</body>
</html>

  输出结果:

$("[attribute!='value']"

选择不存在指定属性,或者指定的属性值不等于给定值的元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p2"></p>
<p id="id_p3"></p> <script type="text/javascript">
$(document).ready(function() {
$("p[class!='class_p1']").html("除了第一个p标签的其它p标签值");
})
</script>
</body>
</html>

  输出结果:

$("[attribute$='value']"

选择指定属性是以给定值结尾的元素。这个比较是区分大小写的。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p2"></p>
<p id="id_p3"></p> <script type="text/javascript">
$(document).ready(function() {
$("p[id$='p2']").html("id为p2结尾的p标签");
})
</script>
</body>
</html>

  输出结果:

$("[attribute^='value']"

选择指定属性是以给定字符串开始的元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p2"></p>
<p id="id_p3"></p> <script type="text/javascript">
$(document).ready(function() {
$("p[id^='id']").html("以id为id开头的的p标签");
})
</script>
</body>
</html>

  输出结果:

$("[attribute]"

选择所有指定属性的元素,该属性可以是任何值。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p2"></p>
<p id="id_p3"></p> <script type="text/javascript">
$(document).ready(function() {
$("p[id]").html("所有id属性的p标签");
})
</script>
</body>
</html>

  输出结果:

$("[attributeFilte[attributeFilter1]r1][attributeFilterN]"                                  

选择匹配所有指定的属性筛选器的元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p2" class="class_p2"></p>
<p id="id_p3"></p> <script type="text/javascript">
$(document).ready(function() {
$("p[id='id_p2'][class$='p2']").html("选择id属性为'id_p2',class属性为p2结尾的p标签");
})
</script>
</body>
</html>

  输出结果:

  举例:

  1. $("[href]") 选取所有带有 href 属性的元素。
  2. $("[href='#']") 选取所有带有 href 值等于 "#" 的元素。
  3. $("[href!='#']") 选取所有带有 href 值不等于 "#" 的元素。
  4. $("[href$='.jpg']") 选取所有 href 值以 ".jpg" 结尾的元素。

3.3 jQuery CSS选择器

  jQuery CSS 选择器可用于改变 HTML 元素的 CSS 属性。

  下面的例子把所有 p 元素的背景颜色更改为红色:

$("p").css("background-color","red");

3.4 表单选择器(建议在其之前加上css选择器,结合以下选择器进行过滤)

序号 表单选择器 描述
1

:button Selector

语法:jQuery(":button")

选择所有按钮元素和类型为按钮的元素。
2

:checkbox Selector

语法:jQuery(":checkbox")

选择所有类型为复选框的元素。
3

:checked Selector

语法:jQuery(":checked")

选择所有勾选的元素。
4

:disabled Selector

语法:jQuery(":disabled")

选择所有被禁用的元素。
5

:enabled Selector

语法:jQuery(":enabled")

选择所有可用的(注:未被禁用的元素)的元素。
6

:file Selector

语法:jQuery(":file")

选择所有类型为文件(file)的元素。
7

:focus Selector

语法:jQuery(":focus")

选择当前获取焦点的元素。
8

:image Selector

语法:jQuery(":image")

选择所有图像类型的元素。
9

:input Selector

语法:jQuery(":input")

选择所有input, textarea, select和button元素
10

:password Selector

语法:jQuery(":password")

选择所有类型为密码的元素。
11

:radio Selector

语法:jQuery(":radio")

选择所有类型为单选框的元素。
12                       

:submit Selector

语法:jQuery(":submit")

选择所有类型为提交的元素。                                                                                                                                                                                                                                                         

  举例1:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
textarea {
height: 35px;
}
div {
color: red;
}
fieldset {
margin: 0px;
padding: 0px;
border-width: 0px;
}
.marked {
background-color: yellow;
border: 3px solid red;
}
</style>
</head> <body>
<form>
<fieldset>
<input type="button" value="Input Button"/>
<input type="checkbox"/>
<input type="file"/>
<input type="hidden"/>
<input type="image"/>
<input type="password"/>
<input type="radio"/>
<input type="reset"/>
<input type="submit"/>
<input type="text"/>
<select>
<option>Option</option>
</select>
<textarea></textarea>
<button>Button</button>
</fieldset> </form>
<script>
// 查找出所有的按钮,并对其添加marked类
$(document).ready(function() {
// var input = $(":button").addClass("marked"); // 1.1 选择所有的button
// var input = $("input:button").addClass("marked"); // 1.2 选择所有的表单button(input type="button"的元素)
// var input = $("input:checkbox").addClass("marked"); // 2. 选择所有类型为复选框的元素
// var input = $("input:checked").addClass("marked"); // 3. 选择所有勾选的元素。
// var input = $("input:file").addClass("marked"); // 6. 选择所有类型为文件(file)的元素。
// var input = $("input:focus").addClass("marked"); // 7. 选择当前获取焦点的元素。
// var input = $("input:image").addClass("marked"); // 8. 选择所有图像类型的元素。
// var input = $(":input").addClass("marked"); // 9. 选择所有的表单元素
// var input = $("input:password").addClass("marked"); // 10. 选择所有类型为密码的元素。
// var input = $("input:radio").addClass("marked"); // 11. 选择所有类型为单选框的元素。
var input = $("input:submit").addClass("marked"); // 12. 选择所有类型为提交的元素。
}); </script>
</body>
</html>

  输出结果:

  举例2(:disabled Selector):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
textarea {
height: 35px;
}
div {
color: red;
}
fieldset {
margin: 0px;
padding: 0px;
border-width: 0px;
}
.marked {
background-color: yellow;
border: 3px solid red;
}
</style>
</head> <body>
<form>
<input name="email", disabled="disabled"/>
<input name="id"/>
</form>
<script>
// 查找所有被禁用的元素
$(document).ready(function() {
$("input:disabled").val("Haha");
}); </script>
</body>
</html>

  输出结果:

3.5 可见性选择器:jQuery(":hidden") 和 jQuery(":visiable")

序号 可见性过滤 描述
1

hidden selector

语法:jQuery(":hidden")

选择所有隐藏的元素。

补充(元素可以被认为是隐藏的几种情况):

  1. 它们的CSS display值时none;
  2. 它们是type="hidden"的表单元素;
  3. 它们的宽度和高度都设置为0;
  4. 一个祖先元素是隐藏的,因此该元素是不会在页面上显示。
2                          

visible selector

语法:jQuery(":visible")

选择所有可见的元素。

如果元素占据文档中一定的空间,元素被认为是可见的。可见元素的宽度和高度,是大于零。

因此:元素的visible: hidden 或者 opacity: 0 被认为是可见的,因为它们仍然占用控件布局。

不在文档中的元素是被认为隐藏的,jQuery没有办法知道它们是否是可见的,因为元素可见性依赖于适用的样式。

隐藏元素上做动画,元素被认为是可见的,直到动画结束。显示元素上做动画,在动画的开始处该元素被认为是可见的。

  举例:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
.outter {
width: 200px;
height: 200px;
background-color: red;
}
.inner {
width: 100px;
height: 100px;
background-color: yellow;
display: none;
}
</style>
</head> <body>
<div class="outter">
<div class="inner">hidder</div>
</div> <script>
// 检测".inner"是否是隐藏的,如果是,则让其显示出来
$(document).ready(function() {
// $(".outter .inner:hidden").css("display", "block"); // jQuery(":hidden") 选择所有隐藏的元素
$(".outter:visible").css("display", "none"); // jQuery(":visiable") 选择所有可见的元素
}); </script>
</body>
</html>

  输出结果(jQuery(":hidden") 选择所有隐藏的元素):

  输出结果(jQuery(":visible") 选择所有可见的元素):

  显示为空(即全部隐藏)。

3.6 更多的选择器实例

语法 描述
$(this) 当前 HTML 元素
$("p") 所有 <p> 元素
$("p.intro") 所有 class="intro" 的 <p> 元素
$(".intro") 所有 class="intro" 的元素
$("#intro") id="intro" 的元素
$("ul li:first") 每个 <ul> 的第一个 <li> 元素
$("[href$='.jpg']") 所有带有以 ".jpg" 结尾的属性值的 href 属性
$("div#intro .head")                                       id="intro" 的 <div> 元素中的所有 class="head" 的元素                                                                                                                                                                                               

  选择多个元素(中间用 英文逗号 "," 隔开):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
</head> <body> <p class="class_p1"></p>
<p id="id_p1"></p> <script type="text/javascript">
$(document).ready(function() {
$(".class_p1, #id_p1").html("我们是一家人");
})
</script>
</body>
</html>

  如需完整的参考手册,请访问我们的 jQuery 选择器参考手册

3.7 jQuery 名称冲突(如与Prototype都使用到$符号)

  jQuery 使用 $ 符号作为 jQuery 的简介方式。

  某些其他 JavaScript 库中的函数(比如 Prototype)同样使用 $ 符号。

  jQuery 使用名为 noConflict() 的方法来解决该问题。

  var jq=jQuery.noConflict(),帮助您使用自己的名称(比如 jq)来代替 $ 符号。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> // // 方式 1
// $(document).ready(function() {
// $("button").click(function() {
// $("#p1").hide();
// });
// });
// // 方式 2
// $.noConflict();
// jQuery(document).ready(function() {
// jQuery("button").click(function() {
// jQuery("#p1").hide();
// });
// }); // 方式 3
var jq = jQuery.noConflict();
jq(document).ready(function() {
jq("button").click(function() {
jq("#p1").hide();
});
});
</script>
</head> <body> <p id="p1">This is a paragraph</p>
<button>Click me</button> </body>
</html>

  输出结果:略。

4、jQuery效果

  如需全面查阅 jQuery 效果,请参考 jQuery 效果参考手册

4.1 隐藏、显示和切换

(1)jQuery hide()和show()方法

  通过 jQuery,您可以使用 hide() 和 show() 方法来隐藏和显示 HTML 元素:

  语法:

$(selector).hide(speed, callback);

$(selector).show(speed, callback);

  如下例子所示,通过点击id为"butHide"或者"butShow"按钮来隐藏或者显示<p>元素

$("#butHide").click(function() {
$("p").hide();
}); $("#butShow").click(function() {
$("p").show();
});

  举例1:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".ex .hide").click(function() {
$(this).parents(".ex").hide("slow");
});
});
</script> <style type="text/css">
div.ex {
background-color:#e5eecc;
padding:7px;
border:solid 1px #c3c3c3;
}
</style>
</head> <body> <h3>中国办事处</h3>
<div class="ex">
<button class="hide" type="button">隐藏</button>
<p>联系人:张先生<br />
北三环中路 100 号<br />
北京</p>
</div> <h3>美国办事处</h3>
<div class="ex">
<button class="hide" type="button">隐藏</button>
<p>联系人:David<br />
第五大街 200 号<br />
纽约</p>
</div> </body>
</html>

  输出结果:略。

  举例2:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#hide").click(function() {
$("#p1").hide();
});
$("#show").click(function() {
$("#p1").show();
});
});
</script>
</head> <body> <p id="p1">如果点击“隐藏”按钮,我就会消失。</p>
<button id="hide" type="button">隐藏</button>
<button id="show" type="button">显示</button> </body>
</html>

  输出结果:略。

(2)jQuery toggle()方法

  通过 jQuery,您可以使用 toggle() 方法来切换 hide() 和 show() 方法。

  语法:

$(selector).toggle(speed,callback);

  显示被隐藏的元素,并隐藏已显示的元素:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#switch").click(function() {
$("p").toggle();
});
});
</script>
</head> <body> <button id="switch" type="button">切换</button>
<p>这是一个段落。</p>
<p>这是另一个段落。</p> </body>
</html>

  输出结果:略。

  可选的 speed 参数规定隐藏/显示的速度,可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是 toggle() 方法完成后所执行的函数名称。

4.2 淡入和淡出(四种 fade 方法)

  jQuery Fading 方法,通过 jQuery,可以实现元素的淡入淡出效果。

  jQuery 拥有下面四种 fade 方法:

  • fadeIn()
  • fadeOut()
  • fadeToggle()
  • fadeTo()

(1)jQuery fadeIn() 方法

  jQuery fadeIn() 用于淡入已隐藏的元素。

  语法:

$(selector).fadeIn(speed,callback);

  可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是 fading 完成后所执行的函数名称。

  下面的例子演示了带有不同参数的 fadeIn() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head> <body> <p>演示带有不同参数的 fadeIn() 方法。</p>
<button>点击这里,使三个矩形淡入</button>
<br><br>
<div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div>    <!--display:none,默认该div区域不显示-->
<br>
<div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div> <!--display:none,默认该div区域不显示-->
<br>
<div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div> <!--display:none,默认该div区域不显示--> </body>
</html>

  输出结果:

(2)jQuery fadeOut() 方法

  jQuery fadeOut() 方法用于淡出可见元素。

  语法:

$(selector).fadeOut(speed,callback);

  可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是 fading 完成后所执行的函数名称。

  下面的例子演示了带有不同参数的 fadeOut() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("#div1").fadeOut();
$("#div2").fadeOut("slow");
$("#div3").fadeOut(3000);
});
});
</script>
</head> <body> <p>演示带有不同参数的 fadeOut() 方法。</p>
<button>点击这里,使三个矩形淡出</button>
<br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
<br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div>
<br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div> </body>
</html>

  输出结果:可以看到三幅图片逐渐淡出。

(3)jQuery fadeToggle() 方法

  jQuery fadeToggle() 方法可以在 fadeIn() 与 fadeOut() 方法之间进行切换。

  如果元素已淡出,则 fadeToggle() 会向元素添加淡入效果。

  如果元素已淡入,则 fadeToggle() 会向元素添加淡出效果。

  语法:

$(selector).fadeToggle(speed,callback);

  可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是 fading 完成后所执行的函数名称。

  下面的例子演示了带有不同参数的 fadeToggle() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
});
</script>
</head> <body> <p>演示带有不同参数的 fadeToggle() 方法。</p>
<button>点击这里,使三个矩形淡入淡出</button>
<br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
<br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div>
<br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div> </body>
</html>

  输出结果:点击按钮可以看到三幅图片逐渐淡入淡出切换。

(4)jQuery fadeTo() 方法

  jQuery fadeTo() 方法允许渐变为给定的不透明度(值介于 0 与 1 之间)。

  语法:

$(selector).fadeTo(speed,opacity,callback);

  必需的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  fadeTo() 方法中必需的 opacity 参数将淡入淡出效果设置为给定的不透明度(值介于 0 与 1 之间)。

  可选的 callback 参数是该函数完成后所执行的函数名称。

  下面的例子演示了带有不同参数的 fadeTo() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("#div1").fadeTo("slow",0.15);
$("#div2").fadeTo("slow",0.4);
$("#div3").fadeTo("slow",0.7);
});
});
</script>
</head> <body> <p>演示带有不同参数的 fadeTo() 方法。</p>
<button>点击这里,使三个矩形淡出</button>
<br><br>
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>
<br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div>
<br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div> </body>
</html>

  输出结果:点击按钮可以看到三幅图片透明度发生改变。

4.3 滑动

  jQuery 滑动方法可使元素上下滑动。

  jQuery 滑动方法。通过 jQuery,您可以在元素上创建滑动效果。

  jQuery 拥有以下滑动方法:

  • slideDown()
  • slideUp()
  • slideToggle()

(1)jQuery slideDown() 方法

  jQuery slideDown() 方法用于向下滑动元素。

  语法:

$(selector).slideDown(speed,callback);

  可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是滑动完成后所执行的函数名称。

  下面的例子演示了 slideDown() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p.flip").click(function() {
$("div.panel").slideDown("slow");
});
}); <!--当前用例中上述代码等价于-->
<!-- $(document).ready(function() { -->
<!-- $(".flip").click(function() { -->
<!-- $(".panel").slideDown("slow"); -->
<!-- }); -->
<!-- }); -->
</script> <style type=text/css>
div.panel p.flip {
margin:0px;
padding:5px;
text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
div.panel {
height:120px;
display:none;
}
</style>
</head> <body> <div class="panel">
<p>W3School - 领先的 Web 技术教程站点</p>
<p>在 W3School,你可以找到你所需要的所有网站建设教程。</p>
</div> <p class="flip">请点击这里</p> </body>
</html>

  输出结果:点击<p>元素内容,会出现向下滑动元素。

(2)jQuery slideUp() 方法

  jQuery slideUp() 方法用于向下滑动元素。

  语法:

$(selector).slideUp(speed,callback);

  可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是滑动完成后所执行的函数名称。

  下面的例子演示了 slideUp() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p.flip").click(function() {
$("div.panel").slideUp("slow");
});
}); </script> <style type=text/css>
div.panel p.flip {
margin:0px;
padding:5px;
text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
div.panel {
height:120px;
<!--display:none;-->
}
</style>
</head> <body> <div class="panel">
<p>W3School - 领先的 Web 技术教程站点</p>
<p>在 W3School,你可以找到你所需要的所有网站建设教程。</p>
</div> <p class="flip">请点击这里</p> </body>
</html>

  输出结果:点击<p>元素内容,会出现向上滑动元素。

(3)jQuery slideToggle() 方法

  jQuery slideToggle() 方法可以在 slideDown() 与 slideUp() 方法之间进行切换。

  如果元素向下滑动,则 slideToggle() 可向上滑动它们。

  如果元素向上滑动,则 slideToggle() 可向下滑动它们。

  语法:

$(selector).slideToggle(speed,callback);

  可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是滑动完成后所执行的函数名称。

  下面的例子演示了 slideToggle() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p.flip").click(function() {
$("div.panel").slideToggle("slow");
});
}); </script> <style type=text/css>
div.panel p.flip {
margin:0px;
padding:5px;
text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3;
}
div.panel {
height:120px;
<!--display:none;-->
}
</style>
</head> <body> <div class="panel">
<p>W3School - 领先的 Web 技术教程站点</p>
<p>在 W3School,你可以找到你所需要的所有网站建设教程。</p>
</div> <p class="flip">请点击这里</p> </body>
</html>

  输出结果:点击<p>元素内容,会出现向下滑动元素。再次点击<p>元素内容,会出现向上滑动元素。

4.4 动画/停止动画(animate() / stop() 方法)

(1)jQuery 动画 - animate() 方法

  jQuery animate() 方法用于创建自定义动画。

  语法:

$(selector).animate({params},speed,callback);

  必需的 params 参数定义形成动画的 CSS 属性。

  可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。

  可选的 callback 参数是动画完成后所执行的函数名称。

  下面的例子演示 animate() 方法的简单应用;它把 <div> 元素移动到左边,直到 left 属性等于 250 像素为止:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("div").animate({left:'250px'});
});
}); </script> </head> <body> <button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div> </body>
</html>

  输出结果:点击按钮,div元素区域会出现从左向右的动画。

  提示:默认地,所有 HTML 元素都有一个静态位置,且无法移动。

  如需对位置进行操作,要记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute!

(1.1)jQuery animate() - 操作多个属性

  请注意,生成动画的过程中可同时使用多个属性:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("div").animate({
left:'250px',
opacity:'0.5',
height:'150px',
width:'150px'
});
});
}); </script> </head> <body> <button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div> </body>
</html>

  提示:可以用 animate() 方法来操作所有 CSS 属性吗?

  是的,几乎可以!不过,需要记住一件重要的事情:当使用 animate() 时,必须使用 Camel 标记法书写所有的属性名,比如,必须使用 paddingLeft 而不是 padding-left,使用 marginRight 而不是 margin-right,等等。

  同时,色彩动画并不包含在核心 jQuery 库中。

  如果需要生成颜色动画,您需要从 jQuery.com 下载 Color Animations 插件。

(1.2)jQuery animate() - 使用相对值

  也可以定义相对值(该值相对于元素的当前值)。需要在值的前面加上 += 或 -=:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("div").animate({
left:'250px',
height:'+=150px',
width:'+=150px'
});
});
}); </script> </head> <body> <button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div> </body>
</html>

  输出结果:略。

(1.3)jQuery animate() - 使用预定义的值

  您甚至可以把属性的动画值设置为 "show"、"hide" 或 "toggle":

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("div").animate({
height:'toggle'
});
});
}); </script> </head> <body> <button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div> </body>
</html>

  输出结果:略。

(1.4)jQuery animate() - 使用队列功能

  默认地,jQuery 提供针对动画的队列功能。

  这意味着如果您在彼此之后编写多个 animate() 调用,jQuery 会创建包含这些方法调用的“内部”队列。然后逐一运行这些 animate 调用。

  举例1(隐藏,如果您希望在彼此之后执行不同的动画,那么我们要利用队列功能):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
var div = $("div");
div.animate({height:'300px',opacity:'0.4'},"slow");
div.animate({width:'300px',opacity:'0.8'},"slow");
div.animate({height:'100px',opacity:'0.4'},"slow");
div.animate({width:'100px',opacity:'0.8'},"slow");
});
}); </script> </head> <body> <button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div> </body>
</html>

  输出结果:略。

  举例2(下面的例子把 <div> 元素移动到右边,然后增加文本的字号):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
var div=$("div");
div.animate({left:'100px'},"slow");
div.animate({fontSize:'3em'},"slow");
});
}); </script> </head> <body> <button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;width:200px;position:absolute;">HELLO</div> </body>
</html>

  输出结果:略。

(2)jQuery 停止动画 - stop() 方法

  jQuery stop() 方法用于在动画或效果完成前对它们进行停止。

  jQuery stop() 方法用于停止动画或效果,在它们完成之前。

  stop() 方法适用于所有 jQuery 效果函数,包括滑动、淡入淡出和自定义动画。

  语法:

$(selector).stop(stopAll,goToEnd);

  可选的 stopAll 参数规定是否应该清除动画队列。默认是 false,即仅停止活动的动画,允许任何排入队列的动画向后执行。

  可选的 goToEnd 参数规定是否立即完成当前动画。默认是 false。

  因此,默认地,stop() 会清除在被选元素上指定的当前动画。

  举例1(jQuery stop() 滑动,下面的例子演示 stop() 方法,不带参数):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#flip").click(function() {
$("#panel").slideDown(5000);
});
$("#stop").click(function() {
$("#panel").stop();
});
}); </script> <style>
#panel #flip {
text-align: center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
#panel {
padding:50px;
display:none;
}
</style>
</head> <body> <button id="stop">停止滑动</button>
<div id="flip">点击这里,向下滑动面板</div>
<div id="panel">Hello world!</div> </body>
</html>

  输出结果:略。

  举例2(jQuery stop() 动画(带有参数)):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#start").click(function(){
$("div").animate({left:'100px'},5000);
$("div").animate({fontSize:'3em'},5000);
}); $("#stop").click(function(){
$("div").stop();
}); $("#stop2").click(function(){
$("div").stop(true);
}); $("#stop3").click(function(){
$("div").stop(true,true);
});
}); </script>
</head> <body> <button id="start">开始</button>
<button id="stop">停止</button>
<button id="stop2">停止所有</button>
<button id="stop3">停止但要完成</button>
<p><b>"开始"</b> 按钮会启动动画。</p>
<p><b>"停止"</b> 按钮会停止当前活动的动画,但允许已排队的动画向前执行。</p>
<p><b>"停止所有"</b> 按钮停止当前活动的动画,并清空动画队列;因此元素上的所有动画都会停止。</p>
<p><b>"停止但要完成"</b> 会立即完成当前活动的动画,然后停下来。</p> <div style="background:#98bf21;height:100px;width:200px;position:absolute;">HELLO</div> </body>
</html>

  输出结果:

开始 停止 停止所有 停止但要完成

"开始" 按钮会启动动画。

"停止" 按钮会停止当前活动的动画,但允许已排队的动画向前执行。

"停止所有" 按钮停止当前活动的动画,并清空动画队列;因此元素上的所有动画都会停止。

"停止但要完成" 会立即完成当前活动的动画,然后停下来。

4.5 Callback/Chaning

  Callback 函数在当前动画 100% 完成之后执行。

(1)jQuery 动画的问题

  许多 jQuery 函数涉及动画。这些函数也许会将 speed 或 duration 作为可选参数。

  例子:$("p").hide("slow")

  speed 或 duration 参数可以设置许多不同的值,比如 "slow", "fast", "normal" 或毫秒。

$("button").click(function(){
$("p").hide(1000);
});

  由于 JavaScript 语句(指令)是逐一执行的 - 按照次序,动画之后的语句可能会产生错误或页面冲突,因为动画还没有完成。

  为了避免这个情况,您可以以参数的形式添加 Callback 函数。

1.2 jQuery Callback函数

  当动画100%完成后,即调用Callback函数。

典型的语法:

$(selector).hide(speed,callback)

  callback 参数是一个在 hide 操作完成后被执行的函数。

错误(没有callback):

$("p").hide(1000);
alert("The paragraph is now hidden");

  举例说明:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("p").hide(2000);
alert("The paragraph is now hidden");
});
}); </script>
</head> <body> <button type="button">Hide</button>
<p>This is a paragraph with little content.</p> </body>
</html>

正确(有callback):

$("p").hide(1000, function() {
alert("The paragraph is now hidden");
});

  举例说明:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("p").hide(2000, function() {
alert("The paragraph is now hidden")
});
});
}); </script>
</head> <body> <button type="button">Hide</button>
<p>This is a paragraph with little content.</p> </body>
</html>

  结论:如果您希望在一个涉及动画的函数之后来执行语句,请使用 callback 函数。

(3)jQuery Chaning(方法链接)

  直到现在,我们都是一次写一条 jQuery 语句(一条接着另一条)。

  不过,有一种名为链接(chaining)的技术,允许我们在相同的元素上运行多条 jQuery 命令,一条接着另一条。

  提示:这样的话,浏览器就不必多次查找相同的元素。

  如需链接一个动作,您只需简单地把该动作追加到之前的动作上。

  举例(下面的例子把 css(), slideUp(), and slideDown() 链接在一起。"p1" 元素首先会变为红色,然后向上滑动,然后向下滑动):

  通过 jQuery,您可以把动作/方法链接起来。

  Chaining 允许我们在一条语句中允许多个 jQuery 方法(在相同的元素上)。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
<!-- $(document).ready(function() { -->
<!-- $("button").click(function() { -->
<!-- $("p").css("color","red").slideUp(2000).slideDown(2000); -->
<!-- }); -->
<!-- }); --> <!--或者写成如下语句,jQuery 会抛掉多余的空格,并按照一行长代码来执行上面的代码行-->
$(document).ready(function() {
$("button").click(function() {
$("p").css("color","red")
.slideUp(2000)
.slideDown(2000);
});
}); </script>
</head> <body> <p id="p1">jQuery 乐趣十足!</p>
<button>点击这里</button> </body>
</html>

  如果需要,我们也可以添加多个方法调用。

  提示:当进行链接时,代码行会变得很差。不过,jQuery 在语法上不是很严格;您可以按照希望的格式来写,包含折行和缩进。

5、jQuery HTML文档操作

  如需有关 jQuery HTML 方法的完整内容,请访问以下参考手册:

5.1 jQuery DOM 操作

  jQuery 中非常重要的部分,就是操作 DOM 的能力。

  jQuery 提供一系列与 DOM 相关的方法,这使访问和操作元素和属性变得很容易。

  提示:DOM = Document Object Model(文档对象模型)

  DOM 定义访问 HTML 和 XML 文档的标准:

  “W3C 文档对象模型独立于平台和语言的界面,允许程序和脚本动态访问和更新文档的内容、结构以及样式。”

5.2 获得内容和属性

(1)获取内容 - text()、html() 以及 val()

  三个简单实用的用于 DOM 操作的 jQuery 方法:

  • text() - 设置或返回所选元素的文本内容
  • html() - 设置或返回所选元素的内容(包括 HTML 标记)
  • val() - 设置或返回表单字段的值

  举例1(下面的例子演示如何通过 jQuery text() 和 html() 方法来获得内容):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function() {
$("#btn1").click(function() {
alert("Text: " + $("#test1").text());
});
$("#btn2").click(function() {
alert("HTML: " + $("#test1").html());
});
$("#btn3").click(function() {
alert("Value: " + $("#test2").val());
});
}); </script>
</head> <body> <p id="test1">这是段落中的<b>粗体</b>文本。</p>
<button id="btn1">显示 Text</button>
<button id="btn2">显示 HTML</button>
<br /> <p>姓名:<input type="text" id="test2" value="米老鼠"></p>
<button id="btn3">显示 Value</button> </body>
</html>

  输出结果:

这是段落中的粗体文本。

显示 Text 显示 HTML

姓名:

显示 Value

(2)获取属性 - attr()

  jQuery attr() 方法用于获取属性值。

  举例(下面的例子演示如何获得链接中 href 属性的值):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function() {
$("button").click(function() {
alert($("#w3s").attr("href"));
});
}); </script>
</head> <body> <p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p>
<button>显示 href 值</button> </body>
</html>

  输出结果:

W3School.com.cn

显示 href 值

5.3 设置内容和属性

(1)设置内容 - text()、html() 以及 val()

  我们将使用前一章中的三个相同的方法来设置内容:

  • text() - 设置或返回所选元素的文本内容
  • html() - 设置或返回所选元素的内容(包括 HTML 标记)
  • val() - 设置或返回表单字段的值

  下面的例子演示如何通过 text()、html() 以及 val() 方法来设置内容:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function() {
$("#btn1").click(function() {
$("#test1").text("Hello, world!");
});
$("#btn2").click(function() {
$("#test2").html("<b>Hello, world!</b>");
});
$("#btn3").click(function() {
$("#test3").val("Dolly Duck");
});
}); </script>
</head> <body> <p id="test1">这是段落。</p>
<p id="test2">这是另一个段落。</p>
<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>
<button id="btn1">设置文本</button>
<button id="btn2">设置 HTML</button>
<button id="btn3">设置值</button> </body>
</html>

  输出结果:

这是段落。

这是另一个段落。

Input field:

设置文本 设置 HTML 设置值

(2)text()、html() 以及 val()的回调函数

  上面的三个 jQuery 方法:text()、html() 以及 val(),同样拥有回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。

  下面的例子演示带有回调函数的 text() 和 html():

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function() {
$("#btn1").click(function() {
$("#test1").text(function(i, origText){
return "Old text: " + origText + " New text: Hello world! (index: " + i + ")";
});
});
$("#btn2").click(function() {
$("#test2").html(function(i, origText){
return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")";
});
});
}); </script>
</head> <body> <p id="test1">这是<b>粗体</b>文本。</p>
<p id="test2">这是另一段<b>粗体</b>文本。</p>
<button id="btn1">显示旧/新文本</button>
<button id="btn2">显示旧/新 HTML</button> </body>
</html>

  输出结果:

这是粗体文本。

这是另一段粗体文本。

显示旧/新文本 显示旧/新 HTML

(3)设置内容 - attr()

  jQuery attr() 方法也用于设置/改变属性值。

  举例1(下面的例子演示如何改变(设置)链接中 href 属性的值):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function() {
$("button").click(function() {
$("#w3s").attr("href","http://www.w3school.com.cn/jquery");
});
}); </script>
</head> <body> <p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p>
<button>改变 href 值</button>
<p>请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。</p> </body>
</html>

  输出结果:

W3School.com.cn

改变 href 值

请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。

  举例2(attr() 方法也允许您同时设置多个属性。下面的例子演示如何同时设置 href 和 title 属性):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function() {
$("button").click(function() {
$("#w3s").attr({"href","http://www.w3school.com.cn/jquery", "title" : "W3School jQuery Tutorial"});
});
}); </script>
</head> <body> <p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p>
<button>改变 href 值</button>
<p>请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。</p> </body>
</html>

  输出结果:

W3School.com.cn

改变 href 值

请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。

(4)attr() 的回调函数

  jQuery 方法 attr(),也提供回调函数。回调函数由两个参数:被选元素列表中当前元素的下标,以及原始(旧的)值。然后以函数新值返回您希望使用的字符串。

  下面的例子演示带有回调函数的 attr() 方法:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function() {
$("button").click(function() {
$("#w3s").attr("href", function(i, origValue) {
alert(origValue + "/jquery");
});
});
}); </script>
</head> <body> <p><a href="http://www.w3school.com.cn" id="w3s">W3School.com.cn</a></p>
<button>改变 href 值</button>
<p>请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。</p> </body>
</html>

  输出结果:

W3School.com.cn

改变 href 值

请把鼠标指针移动到链接上,或者点击该链接,来查看已经改变的 href 值。

5.3 添加元素(添加新的 HTML 内容)

  参考:http://www.w3school.com.cn/jquery/jquery_dom_add.asp

  我们将学习用于添加新内容的四个 jQuery 方法:

  • append() - 在被选元素的结尾插入内容
  • prepend() - 在被选元素的开头插入内容
  • after() - 在被选元素之后插入内容
  • before() - 在被选元素之前插入内容

(1)jQuery append() 方法

  jQuery append() 方法在被选元素的结尾插入内容。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
}); $("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
}); </script>
</head> <body> <p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">追加文本</button>
<button id="btn2">追加列表项</button> </body>
</html>

  输出结果:

This is a paragraph.

This is another paragraph.

  1. List item 1
  2. List item 2
  3. List item 3

追加文本 追加列表项

(2)jQuery prepend() 方法

  jQuery prepend() 方法在被选元素的开头插入内容。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("#btn1").click(function(){
$("p").prepend(" <b>Appended text</b>.");
}); $("#btn2").click(function(){
$("ol").prepend("<li>Appended item</li>");
});
}); </script>
</head> <body> <p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">追加文本</button>
<button id="btn2">追加列表项</button> </body>
</html>

  输出结果:

This is a paragraph.

This is another paragraph.

  1. List item 1
  2. List item 2
  3. List item 3

追加文本 追加列表项

(3)通过 append() 和 prepend() 方法添加若干新元素

  在上面的例子中,我们只在被选元素的开头/结尾插入文本/HTML。

  不过,append() 和 prepend() 方法能够通过参数接收无限数量的新元素。可以通过 jQuery 来生成文本/HTML(就像上面的例子那样),或者通过 JavaScript 代码和 DOM 元素。

  在下面的例子中,我们创建若干个新元素。这些元素可以通过 text/HTML、jQuery 或者 JavaScript/DOM 来创建。然后我们通过 append() 方法把这些新元素追加到文本中(对 prepend() 同样有效):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> function appendText()
{
var txt1="<p>Text.</p>"; // 以 HTML 创建新元素
var txt2=$("<p></p>").text("Text."); // 以 jQuery 创建新元素
var txt3=document.createElement("p");
txt3.innerHTML="Text."; // 通过 DOM 来创建文本
$("body").append(txt1, txt2, txt3); // 追加新元素
} </script>
</head> <body> <p>This is a paragraph.</p>
<button onclick="appendText()">追加文本</button> </body>
</html>

  输出结果:略。

(4)jQuery after() 和 before() 方法

  jQuery after() 方法在被选元素之后插入内容。

  jQuery before() 方法在被选元素之前插入内容。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--寮曠敤jQuery搴擄紝src鍙互鐩存帴鎸囧悜鏈湴涓嬭浇鐨刯Qery搴?->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("#btn1").click(function(){
$("img").before("<b>Before</b>");
}); $("#btn2").click(function(){
$("img").after("<i>After</i>");
});
}); </script>
</head> <body> <img src="/i/eg_w3school.gif" alt="W3School Logo" />
<br><br>
<button id="btn1">Before the &lt;img&gt; insert text</button>
<button id="btn2">After the &lt;img&gt; insert text</button> </body>
</html>

  输出结果:略。

(5)通过 after() 和 before() 方法添加若干新元素

  after() 和 before() 方法能够通过参数接收无限数量的新元素。可以通过 text/HTML、jQuery 或者 JavaScript/DOM 来创建新元素。

  在下面的例子中,我们创建若干新元素。这些元素可以通过 text/HTML、jQuery 或者 JavaScript/DOM 来创建。然后我们通过 after() 方法把这些新元素插到文本中(对 before() 同样有效):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--寮曠敤jQuery搴擄紝src鍙互鐩存帴鎸囧悜鏈湴涓嬭浇鐨刯Qery搴?->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> function afterText()
{
var txt1="<b>I </b>"; // 以 HTML 创建元素
var txt2=$("<i></i>").text("love "); // 通过 jQuery 创建元素
var txt3=document.createElement("big"); // 通过 DOM 创建元素
txt3.innerHTML="jQuery!";
$("img").after(txt1,txt2,txt3); // 在 img 之后插入新元素
} </script>
</head> <body> <img src="/i/eg_w3school.gif" alt="W3School Logo" />
<br><br>
<button onclick="afterText()">After the &lt;img&gt; insert text</button> </body>
</html>

  输出结果:略。

5.4 删除元素

  通过 jQuery,可以很容易地删除已有的 HTML 元素。

  如需删除元素和内容,一般可使用以下两个 jQuery 方法:

  • remove() - 删除被选元素(及其子元素)
  • empty() - 从被选元素中删除子元素

(1)jQuery remove() 方法

  jQuery remove() 方法删除被选元素及其子元素

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!---->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("#div1").remove();
});
}); </script>
</head> <body> <div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div> <br>
<button>delete &lt;div1&gt; element</button> </body>
</html>

  输出结果:略。

(2)jQuery empty() 方法

  jQuery empty() 方法删除被选元素的子元素。

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!---->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("#div1").empty();
});
}); </script>
</head> <body> <div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div> <br>
<button>empty &lt;div1&gt; element</button> </body>
</html>

  输出结果:略。

(3)过滤被删除的元素

  jQuery remove() 方法也可接受一个参数,允许您对被删元素进行过滤。

  该参数可以是任何 jQuery 选择器的语法。

  下面的例子删除 class="italic" 的所有 <p> 元素:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!---->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("p").remove(".italic");
});
}); </script>
</head> <body> <p>This is a paragraph in the div.</p>
<p class="italic"><i>This is another paragraph in the div.</i></p>
<p class="italic"><i>This is another paragraph in the div.</i></p>
<button>delete class="italic" of &lt;p&gt; element</button> </body>
</html>

  输出结果:略。

5.5 获取并设置CSS类(操作CSS)

  jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:

  • addClass() - 向被选元素添加一个或多个类
  • removeClass() - 从被选元素删除一个或多个类
  • toggleClass() - 对被选元素进行添加/删除类的切换操作
  • css() - 设置或返回样式属性

(1)jQuery addClass() 方法

  下面的例子展示如何向不同的元素添加 class 属性。当然,在添加类时,您也可以选取多个元素:

  举例1:

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").addClass("blue");
$("div").addClass("important");
});
}); </script> <!--增加两个class(css属性)-->
<style type="text/css">
.important {
font-weight:bold;
font-size:xx-large;
}
.blue {
color:blue;
}
</style> </head> <body> <h1>标题 1</h1>
<h2>标题 2</h2>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<div>这是非常重要的文本!</div>
<br>
<button>向元素添加类</button> </body>
</html>

  输出结果:略。

  举例2(也可以在 addClass() 方法中规定多个类):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("#div1").addClass("important blue");
});
}); </script> <!--增加两个class(css属性)-->
<style type="text/css">
.important {
font-weight:bold;
font-size:xx-large;
}
.blue {
color:blue;
}
</style> </head> <body> <div id="div1">这是一些文本。</div>
<div id="div2">这是一些文本。</div>
<br>
<button>向第一个 div 元素添加类</button> </body>
</html>

  输出结果:略。

(2)jQuery removeClass() 方法

  下面的例子演示如何不同的元素中删除指定的 class 属性:

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").removeClass("blue");
});
}); </script> <!--增加两个class(css属性)-->
<style type="text/css">
.important {
font-weight:bold;
font-size:xx-large;
}
.blue {
color:blue;
}
</style> </head> <body> <h1 class="blue">标题 1</h1>
<h2 class="blue">标题 2</h2>
<p class="blue">这是一个段落。</p>
<p>这是另一个段落。</p>
<br>
<button>从元素上删除类</button> </body>
</html>

  输出结果:略。

(3)jQuery toggleClass() 方法

  下面的例子将展示如何使用 jQuery toggleClass() 方法。该方法对被选元素进行添加/删除类的切换操作:

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("h1,h2,p").toggleClass("blue");
});
}); </script> <!--增加两个class(css属性)-->
<style type="text/css">
.important {
font-weight:bold;
font-size:xx-large;
}
.blue {
color:blue;
}
</style> </head> <body> <h1>标题 1</h1>
<h2>标题 2</h2>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<br>
<button>从元素上删除类</button> </body>
</html>

  输出结果:略。

(4)jQuery css() 方法

  css() 方法设置或返回被选元素的一个或多个样式属性。

(4.1)返回CSS属性

  如需返回指定的 CSS 属性的值,请使用如下语法:

css("propertyname");

  举例(下面的例子将返回首个匹配元素的 background-color 值):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("p").css("background-color"));
});
}); </script> </head> <body> <h2>这是标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<button>返回 p 元素的背景色</button> </body>
</html>

  输出结果:略。

(4.2)设置CSS属性

  如需设置指定的 CSS 属性的值,请使用如下语法:

css("propertyname","value");

  举例(下面的例子将为所有匹配元素设置 background-color 值):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("p").css("background-color","yellow");
});
}); </script> </head> <body> <h2>这是标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<p>这是一个段落。</p>
<button>返回 p 元素的背景色</button> </body>
</html>

  输出结果:略。

(4.3)设置多个CSS属性

  如需设置多个 CSS 属性,请使用如下语法:

1 css({"propertyname":"value","propertyname":"value",...});

  下面的例子将为所有匹配元素设置 background-color 和 font-size:

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("p").css({"background-color":"yellow","font-size":"200%"});
});
}); </script> </head> <body> <h2>这是标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<p>这是一个段落。</p>
<button>返回 p 元素的背景色</button> </body>
</html>

  输出结果:略。

5.6 尺寸(盒模型)

  jQuery 尺寸 方法。jQuery 提供多个处理尺寸的重要方法:

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

(1)介绍几个概念

  1. margin和padding都是盒模型(Box Model)的重要元素,二者都是用来处理与其他盒子的距离关系进行布局的。
  2. 形象的介绍,夏季女生在地铁遇到色狼变态时有发生,如果选择穿上羽绒服与色狼保持距离,那就是padding内边距,如果选择移动自己的位置远离色狼,那就是margin外边距。
  3. 就与borde边框的位置来看,padding在border边框内,margin在border边框外。
  4. padding内边距会改变盒模型的大小(即宽高),margin则不会。
  5. margin内边距用负值,padding不可以。
<!--padding:内边距,上右下左-->
<!--margin:外边框-->
<!--border:边框-->
<!--width:element宽度-->
<!--height:element高度-->

  并且规范还提供了省略的数值写法,基本如下:

  1. 如果margin只有一个值,表示上右下左的margin同为这个值。例如:margin:10px; 就等于 margin:10px 10px 10px 10px;
  2. 如果 margin 只有两个值,第一个值表示上下margin值,第二个值为左右margin的值。例如:margin:10px 20px; 就等于 margin:10px 20px 10px 20px;
  3. 如果margin有三个值,第一个值表示上margin值,第二个值表示左右margin的值,第三个值表示下margin的值。例如:margin:10px 20px 30px; 就等于 margin:10px 20px 30px 20px;
  4. 如果margin有四个值,那这四个值分别对应上右下左这四个margin值。例如:margin:10px 20px 30px 40px;

(2)jQuery width() 和 height() 方法

  • width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距)。
  • height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)。

(3)jQuery innerWidth() 和 innerHeight() 方法

  • innerWidth() 方法返回元素的宽度(包括内边距)。
  • innerHeight() 方法返回元素的高度(包括内边距)。

(4)jQuery outerWidth() 和 outerHeight() 方法

  • outerWidth() 方法返回元素的宽度(包括内边距和边框)。
  • outerHeight() 方法返回元素的高度(包括内边距和边框)。
  • outerWidth(true) 方法返回元素的宽度(包括内边距、边框和外边距)。
  • outerHeight(true) 方法返回元素的高度(包括内边距、边框和外边距)。

  举例1(下面的例子返回指定的 <div> 元素的宽度和高度,innerWidth/innerHeight, outerWidth/outerHeight):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("#btn1").click(function(){
var txt="";
txt += "Width of div: " + $("#div1").width() + "</br>";
txt += "Height of div: " + $("#div1").height();
$("#div1").html(txt);
}); $("#btn2").click(function(){
var txt="";
txt += "Inner width of div: " + $("#div2").innerWidth() + "</br>";
txt += "Inner height of div: " + $("#div2").innerHeight();
$("#div2").html(txt);
}); $("#btn3").click(function(){
var txt="";
txt += "Width of div: " + $("#div3").width() + "</br>";
txt += "Height of div: " + $("#div3").height() + "</br>";
txt += "Outer width of div: " + $("#div3").outerWidth() + "</br>";
txt += "Outer height of div: " + $("#div3").outerHeight();
$("#div3").html(txt);
}); $("#btn4").click(function(){
var txt="";
txt += "Width of div: " + $("#div4").width() + "</br>";
txt += "Height of div: " + $("#div4").height() + "</br>";
txt += "Outer width of div (margin included): " + $("#div4").outerWidth(true) + "</br>";
txt += "Outer height of div (margin included): " + $("#div4").outerHeight(true);
$("#div4").html(txt);
});
}); </script> </head> <body> <div id="div1" style="height:100px;width:400px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div>
<br>
<button id="btn1">显示 div 的尺寸</button>
<p>width() - 返回元素的宽度。</p>
<p>height() - 返回元素的高度。</p>
<br /> <div id="div2" style="height:100px;width:400px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div>
<br>
<button id="btn2">显示 div 的尺寸</button>
<p>innerWidth() - 返回元素的宽度(包括内边距)。</p>
<p>innerHeight() - 返回元素的高度(包括内边距)。</p> <div id="div3" style="height:100px;width:400px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div>
<br>
<button id="btn3">显示 div 的尺寸</button>
<p>outerWidth() - 返回元素的宽度(包括内边距和边框)。</p>
<p>outerHeight() - 返回元素的高度(包括内边距和边框)。</p> <div id="div4" style="height:150px;width:400px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div>
<br>
<button id="btn4">显示 div 的尺寸</button>
<p>outerWidth(true) - 返回元素的宽度(包括内边距、边框和外边距)。</p>
<p>outerHeight(true) - 返回元素的高度(包括内边距、边框和外边距)。</p> </body>
</html>

  输出结果:略。

  举例2(下面的例子返回文档(HTML 文档)和窗口(浏览器视口)的宽度和高度):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
var txt="";
txt+="Document width/height: " + $(document).width();
txt+="x" + $(document).height() + "\n";
txt+="Window width/height: " + $(window).width();
txt+="x" + $(window).height();
alert(txt);
});
}); </script> </head> <body> <button>显示文档和窗口的尺寸</button> </body>
</html>

  输出结果:略。

  举例3(下面的例子设置指定的 <div> 元素的宽度和高度):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript"> $(document).ready(function(){
$("button").click(function(){
$("#div1").width(320).height(320);
});
}); </script> </head> <body> <div id="div1" style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div>
<br>
<button>调整 div 的尺寸</button> </body>
</html>

  输出结果:略。

6、jQuery遍历

  jQuery 遍历,意为“移动”,用于根据其相对于其他元素的关系来“查找”(或选取)HTML 元素。以某项选择开始,并沿着这个选择移动,直到抵达您期望的元素为止。

  下图展示了一个家族树。通过 jQuery 遍历,您能够从被选(当前的)元素开始,轻松地在家族树中向上移动(祖先),向下移动(子孙),水平移动(同胞)。这种移动被称为对 DOM 进行遍历。

  图示解释:

  • <div> 元素是 <ul> 的父元素,同时是其中所有内容的祖先。
  • <ul> 元素是 <li> 元素的父元素,同时是 <div> 的子元素
  • 左边的 <li> 元素是 <span> 的父元素,<ul> 的子元素,同时是 <div> 的后代。
  • <span> 元素是 <li> 的子元素,同时是 <ul> 和 <div> 的后代。
  • 两个 <li> 元素是同胞(拥有相同的父元素)。
  • 右边的 <li> 元素是 <b> 的父元素,<ul> 的子元素,同时是 <div> 的后代。
  • <b> 元素是右边的 <li> 的子元素,同时是 <ul> 和 <div> 的后代。

  提示:祖先是父、祖父、曾祖父等等。后代是子、孙、曾孙等等。同胞拥有相同的父。

  jQuery 提供了多种遍历 DOM 的方法。

  遍历方法中最大的种类是树遍历(tree-traversal)。

6.1 祖先

  祖先是父、祖父或曾祖父等等。

  通过 jQuery,您能够向上遍历 DOM 树,以查找元素的祖先。

  向上遍历DOM树。 

  这些 jQuery 方法很有用,它们用于向上遍历 DOM 树:

  • parent():返回被选元素的直接父元素。 该方法只会向上一级对 DOM 树进行遍历。
  • parents():返回被选元素的所有祖先元素,它一路向上直到文档的根元素 (<html>)。也可以使用可选参数来过滤对祖先元素的搜索。
  • parentsUntil():返回介于两个给定元素之间的所有祖先元素。

  举例1(parent() 方法,下面的例子返回每个 <span> 元素的的直接父元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
<!--测试parent()方法-->
$("span").parent().css({"color":"red","border":"2px solid red"});
});
</script> <style>
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body> <!--测试parent()方法-->
<p>jQuery parent() 方法,parent() 方法返回被选元素的直接父元素。</p>
<div class="ancestors">
<div style="width:500px;">div (曾祖父)
<ul>ul (祖父)
<li>li (直接父)
<span>span</span>
</li>
</ul>
</div> <div style="width:500px;">div (祖父)
<p>p (直接父)
<span>span</span>
</p>
</div>
</div> </body>
</html>

  输出结果:

  举例2(parents() 方法,下面的例子返回所有 <span> 元素的所有祖先:):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
<!--测试parents()方法-->
$("span").parents().css({"color":"red","border":"2px solid red"});
});
</script> <style>
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body class="ancestors">body (曾曾祖父)
<!--测试parents()方法-->
<div style="width:500px;">div (曾祖父)
<ul>ul (祖父)
<li>li (直接父)
<span>span</span>
</li>
</ul>
</div> </body>
</html>

  输出结果:

  举例2(parentsUntil() 方法,下面的例子返回所有 <span> 元素的所有祖先:):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
<!--parentsUntil()方法-->
$("span").parentsUntil("div").css({"color":"red","border":"2px solid red"});
});
</script> <style>
.ancestors * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body class="ancestors">body (曾曾祖父)
<!--parentsUntil()方法-->
<div style="width:500px;">div (曾祖父)
<ul>ul (祖父)
<li>li (直接父)
<span>span</span>
</li>
</ul>
</div> </body>
</html>

  输出结果:

6.2 后代/子元素过滤/层级

  后代是子、孙、曾孙等等。

  通过 jQuery,您能够向下遍历 DOM 树,以查找元素的后代。

  向下遍历 DOM 树。

(1)方式一(遍历——后代)

  下面是两个用于向下遍历 DOM 树的 jQuery 方法:

  • children():返回被选元素的所有直接子元素。该方法只会向下一级对 DOM 树进行遍历。
  • find():返回被选元素的后代元素,一路向下直到最后一个后代。

(2)方式二(子元素过滤)

序号 子元素过滤 描述
1

:first-child Selector

语法:jQuery("first-child")

选择所有父级元素下的第一个子元素。
2

:last-child Selector

语法:jQuery("last-child")

选择所有父级元素下的最后一个子元素。
3

:first-of-type Selector

语法:jQuery("first-of-type")

选择所有相同的元素名称的第一个兄弟元素。
4

:last-of-type Selector

语法:jQuery("last-of-type")

选择所有相同的元素名称的最后一个兄弟元素。
5                          :first-child Selector
语法:jQuery(":nth-child(index/even/odd/equation)")                                                                
选择所有父级元素下的第n个子元素。                                                                                                                                  

(3)方式三(层级)

序号 层级 描述
1

Child Selector ("parent>child")子元素选择器

语法:jQuery("parent>child")

选择所有制定"parent"元素中指定的"child"的直接子元素

注:

  • parent:任何有效的选择器;
  • child:用来筛选子元素的选择器。
2

descendant selector (后代选择器)

语法:jQuery("ancestor descendant")

选择给定的祖先元素的所有后代元素

注:

  • ancestor:任何有效的选择器;
  • descendant:一个用来筛选后代元素的选择器。
3

next adjacent selector ("pre + next") 相邻选择器

语法:jQuery("prev + next")

选择所有紧接在"prev"元素后的"next"元素。
4                        

Next Siblings Selector ("pre ~ siblings")

语法:jQuery("prev ~ siblings")

匹配"prev"元素之后的所有兄弟元素。具有相同的父元素,并匹配过滤"siblings"选择器。

注:

prev:任何有效的选择器

siblings:一个选择器来过滤第一选择器以后的兄弟元素。(即选择prev之后的所有的同级siblings元素)

  注意:(prev + next) 与 (prev ~ siblings) 之间最值得注意的不通电是他们各自的可及之范围。前者只打到紧随的同级元素,后者扩展了该达到跟随其的所有同级元素。

举例说明(方式一:遍历——后代)

  举例1(children() 方法,下面的例子返回每个 <div> 元素的所有直接子元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div").children().css({"color":"red","border":"2px solid red"});
});
</script> <style>
.descendants * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body>
<div class="descendants" style="width:500px;">div (当前元素)
<p>p (子)
<span>span (孙)</span>
</p>
<p>p (child)
<span>span (孙)</span>
</p>
</div> </body>
</html>

  输出结果:

  举例2(children() 方法,您也可以使用可选参数来过滤对子元素的搜索。下面的例子返回类名为 "1" 的所有 <p> 元素,并且它们是 <div> 的直接子元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div").children(p.1).css({"color":"red","border":"2px solid red"});
});
</script> <style>
.descendants * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body>
<div class="descendants" style="width:500px;">div (当前元素)
<p class="1">p (子)
<span>span (孙)</span>
</p>
<p class="2">p (child)
<span>span (孙)</span>
</p>
</div> </body>
</html>

  输出结果:

  举例3(find() 方法,下面的例子返回属于 <div> 后代的所有 <span> 元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div").find("span").css({"color":"red","border":"2px solid red"});
});
</script> <style>
.descendants * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body>
<div class="descendants" style="width:500px;">div (当前元素)
<p class="1">p (子)
<span>span (孙)</span>
</p>
<p class="2">p (child)
<span>span (孙)</span>
</p>
</div> </body>
</html>

  输出结果:

  举例4(find() 方法,下面的例子返回属于 <div> 后代的所有后代):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div").find("*").css({"color":"red","border":"2px solid red"});
});
</script> <style>
.descendants * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body>
<div class="descendants" style="width:500px;">div (当前元素)
<p class="1">p (子)
<span>span (孙)</span>
</p>
<p class="2">p (child)
<span>span (孙)</span>
</p>
</div> </body>
</html>

  输出结果:

举例说明(方式二:子元素过滤)

  举例1:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
.sogreen {
background-color: green;
}
</style>
</head> <body>
<div>
<span>s11</span>
<span>s12</span>
<span>s13</span>
</div>
<div>
<span>s21</span>
<span>s22</span>
<span>s23</span>
</div>
<div>
<span>s31</span>
<span>s32</span>
<span>s33</span>
</div>
<script>
// $("document").ready(function() {
// $("div :first-child").css("text-decoration", "underline").hover( // hover, $(selector).hover(inFunction,outFunction), 如果只规定了一个函数,则它将会在 mouseover 和 mouseout 事件上运行。
// function() {
// $(this).addClass("sogreen");
// }, function() {
// $(this).removeClass("sogreen");
// }
// )
// }); // $("document").ready(function() {
// $("div :last-child").css("text-decoration", "underline").hover( // hover, $(selector).hover(inFunction,outFunction), 如果只规定了一个函数,则它将会在 mouseover 和 mouseout 事件上运行。
// function() {
// $(this).addClass("sogreen");
// }, function() {
// $(this).removeClass("sogreen");
// }
// )
// }); // $("document").ready(function() {
// $("div span:first-of-type").css("text-decoration", "underline").hover( // hover, $(selector).hover(inFunction,outFunction), 如果只规定了一个函数,则它将会在 mouseover 和 mouseout 事件上运行。
// function() {
// $(this).addClass("sogreen");
// }, function() {
// $(this).removeClass("sogreen");
// }
// )
// }); $("document").ready(function() {
$("div :nth-child(2)").css("text-decoration", "underline").hover( // hover, $(selector).hover(inFunction,outFunction), 如果只规定了一个函数,则它将会在 mouseover 和 mouseout 事件上运行。
function() {
$(this).addClass("sogreen");
}, function() {
$(this).removeClass("sogreen");
}
)
});
</script>
</body>
</html>

  输出结果:

举例说明(方式三:层级)

  举例1(jQuery("parent>child")、jQuery("ancestor descendant")、jQuery("prev + next")):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style> </style>
</head> <body>
<ul class="topnav">
<li>li1</li>
<li>li2</li>
<li>
<ul>
<li>next li1</li>
<li>next li2</li>
<li>next li3</li>
</ul>
</li>
<li>li3</li>
</ul>
<script>
$(document).ready(function() {
// $(".topnav>li").css("border", "1px solid red"); // jQuery("parent>child") 子元素选择器
// $(".topnav li").css("border", "1px solid red"); // jQuery("ancestor descendant") 所有后代选择器
$("li + li").css("border", "1px solid red"); // jQuery("prev + next") 相邻选择器
}); </script>
</body>
</html>

  输出结果(jQuery("parent>child"),即输出直接子元素):

  输出结果(jQuery("ancestor descendant"),输出所有后代元素):

  输出结果(jQuery("prev + next") 相邻选择器):

  举例2(jQuery("prev ~ siblings")):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style> </style>
</head> <body>
<span id="prev">span1</span>
<div>div1</div>
<div>div2</div>
<div>div3
<div>div4</div>
<span>span2</span>
</div> <script>
$(document).ready(function() {
$("#prev ~ div").css("border", "1px solid red");
}); </script>
</body>
</html>

  输出结果:

6.3 同胞

  同胞拥有相同的父元素。

  通过 jQuery,您能够在 DOM 树中遍历元素的同胞元素。

  在 DOM 树中水平遍历。

  有许多有用的方法让我们在 DOM 树进行水平遍历:

  • siblings():返回被选元素的所有同胞元素。
  • next():返回被选元素的下一个同胞元素。该方法只返回一个元素。
  • nextAll():返回被选元素的所有跟随的同胞元素。
  • nextUntil():返回介于两个给定参数之间的所有跟随的同胞元素。
  • prev():
  • prevAll():
  • prevUntil():

  prev(), prevAll() 以及 prevUntil() 方法的工作方式与上面的方法类似,只不过方向相反而已:它们返回的是前面的同胞元素(在 DOM 树中沿着同胞元素向后遍历,而不是向前)。

  举例1(siblings() 方法,下面的例子返回 <h2> 的所有同胞元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("h2").siblings().css({"color":"red","border":"2px solid red"});
});
</script> <style>
.siblings * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body class="siblings">
<div>div (父)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div> </body>
</html>

  输出结果:

  举例2(siblings() 方法,下面的例子返回属于 <h2> 的同胞元素的所有 <p> 元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("h2").siblings("p").css({"color":"red","border":"2px solid red"});
});
</script> <style>
.siblings * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body class="siblings">
<div>div (父)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div> </body>
</html>

  输出结果:

  举例3(next() 方法,下面的例子返回 <h2> 的下一个同胞元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("h2").next().css({"color":"red","border":"2px solid red"});
});
</script> <style>
.siblings * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body class="siblings">
<div>div (父)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div> </body>
</html>

  输出结果:

  举例4(nextAll() 方法,下面的例子返回 <h2> 的所有跟随的同胞元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("h2").nextAll().css({"color":"red","border":"2px solid red"});
});
</script> <style>
.siblings * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body class="siblings">
<div>div (父)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<p>p</p>
</div> </body>
</html>

  输出结果:

  举例5(nextUntil() 方法,下面的例子返回介于 <h2> 与 <h6> 元素之间的所有同胞元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("h2").nextUntil("h6").css({"color":"red","border":"2px solid red"});
});
</script> <style>
.siblings * {
display: block;
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
} </style>
</head> <body class="siblings">
<div>div (父)
<p>p</p>
<span>span</span>
<h2>h2</h2>
<h3>h3</h3>
<h4>h4</h4>
<h5>h5</h5>
<h6>h6</h6>
<p>p</p>
</div> </body>
</html>

  输出结果:

6.4 过滤(搜索特定的元素)/内容过滤

(1)内容过滤

序号 内容过滤 描述

1

:contains() Selector

语法:jQuery(":contains(text)")

选择所有包含制定文本的元素。

注意:text:用来查找的一个文本字符串。这是区分大小写的。匹配的文本可以直接出现在所选的元素中,或者在该元素的任何后代,或者两者兼有。

2

:empty() Selector

语法:jQuery(":empty")

选择所有没有子元素的元素(包括文本节点)。
3

:has() Selector

语法:jQuery(":has(selector)")

选择元素其中至少包含制定选择器匹配的一个种元素。
4                    

:parent() Selector

语法:jQuery(":parent")

选择所有含有子元素或者文本的父级元素。                                                                                                                                                                                                              

  举例1(:contains() Selector):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
.sogreen {
background-color: green;
}
</style>
</head> <body>
<div>John Resig</div>
<div>gggg Resig</div>
<div>Malcom John Sinclair</div>
<div>J.ohn</div>
<script>
$("document").ready(function() {
$("div:contains('John')").css("text-decoration", "underline");
});
</script>
</body>
</html>

  输出结果:

  举例2(:empty() Selector):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
</style>
</head> <body>
<table border="1">
<tr>
<td>TD #0</td>
<td>TD #1</td>
<td>TD #2</td>
</tr>
<tr>
<td>TD #3</td>
<td></td>
<td>TD #5</td>
</tr>
<tr>
<td></td>
<td>TD #7</td>
<td></td>
</tr>
</table> <script>
$("document").ready(function() {
$("td:empty").text("was empty").css("background-color", "red");
});
</script>
</body>
</html>

  输出结果:

  举例3(:has() Selector):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
.test {
border: 1px solid green;
}
</style>
</head> <body>
<div>
<p>Hello, this is a paragraph.</p>
</div>
<div>
Hello, this is a paragraph (with no p).
</div>
<script>
// 给所有的包含p标签的元素,添加一个test类
$("document").ready(function() {
$("div:has(p)").addClass("test");
});
</script>
</body>
</html>

  输出结果:

(2)遍历——过滤

  三个最基本的过滤方法是:first(), last() 和 eq(),它们允许您基于其在一组元素中的位置来选择一个特定的元素。

  其他过滤方法,比如 filter() 和 not() 允许您选取匹配或不匹配某项指定标准的元素。

  • first():返回被选元素的首个元素。
  • last():返回被选元素的最后一个元素。
  • eq():返回被选元素中带有指定索引号的元素。索引号从 0 开始,因此首个元素的索引号是 0 而不是 1。
  • filter():允许您规定一个标准。不匹配这个标准的元素会被从集合中删除,匹配的元素会被返回。
  • not():返回不匹配标准的所有元素。提示:not() 方法与 filter() 相反。

(3)基础过滤

1

:animated Selector

语法:$(":animated")

选择所有正在执行动画效果的元素。
2

:eq() Selector

语法:

  1. $(":eq(index)"):index: 要匹配元素的索引值(从0开始计数)
  2. $(":eq(-index)"):index: 要匹配元素的索引值(从最后一个数开始计数)
在匹配的集合中选择索引值为index的元素
3

:even Selector

语法:$(":even")

选择索引值为偶数的元素,从0开始计数,也可以查看odd(奇数)。

注意:这是基于0的索引所以:even选择器是选择第一个元素,第三个元素,依次类推在匹配。

4

:first Selector

语法:$(":first")

选择第一个匹配的元素。

5

:focus Selector

语法:$(":focus")

选择当前获取焦点的元素。
6

:header Selector

语法:$(":header")

选择所有标题元素,像h1, h2, h3等。
7

:last Selector

语法:$(":last")

选择最后一个匹配的元素。
8

:gt Selector

语法:$(":gt(index)")或者$(":gt(-index)")

选择匹配集合中所有大于给定index(索引值)的元素。
9

:lt Selector

语法:$(":lt(index)")或者$(":lt(-index)")

选择匹配集合中所有索引值小于给定index参数的元素。
10          

:not() Selector

语法:$(":not(selector)")

选择所有元素去除不匹配给定的选择器的元素。                                                                                                     

  举例1(语法:$(":animated"),选择所有正在执行动画效果的元素。):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
div {
width: 100px;
height: 100px;
background-color: yellow;
float: left;
border: 1px solid #aaaaaa;
margin: 0px 5px;
}
.colored {
background-color: green;
}
</style>
</head> <body>
<button id="btn">run</button>
<div></div>
<div id="mover"></div>
<div></div> <script>
$("document").ready(function() {
$("#btn").click(function() {
$("div:animated").toggleClass("colored");
});
function animatedIt() {
$("#mover").slideToggle("slow", animatedIt); // 用滑动动画显示/隐藏一个元素,这里用的是递归调用(无限循环的意思),slow代表600ms的延时时间结束
}
animatedIt();
});
</script>
</body>
</html>

  输出结果:

  举例2(:first Selector、:last Selector、:eq() Selector、:even Selector):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
div {
width: 100px;
height: 50px;
background-color: yellow;
/* float: left; */
border: 1px solid #aaaaaa;
margin: 0px 5px;
}
.colored-1 {
background-color: green;
}
.colored-2 {
background-color: red;
}
.colored-3 {
background-color: blue;
}
</style>
</head> <body>
<div></div>
<div></div>
<div></div> <script>
$("document").ready(function() {
// $("div:first").toggleClass("colored-1"); // 选择第一个div元素
// $("div:eq(1)").toggleClass("colored-2"); // 选择索引值为1的元素
// $("div:even").toggleClass("colored-3"); // 选择索引值为偶数的元素
$("div:last").toggleClass("colored-1"); // 选择最后一个div元素
});
</script>
</body>
</html>

  输出结果:

  举例3(:focus Selector,选择当前获取焦点的元素):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
.focused {
background-color: #abcdef;
}
</style>
</head> <body>
<div id="content">
<input tabindex="1"/>
<input tabindex="2"/>
<select tabindex="1">
<option>Select menu</option>
</select>
<div tabindex="4">
This is a div.
</div>
</div> <script>
$("document").ready(function() {
$("#content").delegate("*", "focus blur", function(event) {
var e = $(this);
setTimeout(function() {
e.toggleClass("focused", e.is(":focus"));
}, 0); // jQuery, method-1. setTimeout(code, milliseconds, param1, param2, ...), method-2. setTimeout(function, milliseconds, param1, param2, ...)
});
});
</script>
</body>
</html>

  输出结果:

  举例4(:lt Selector,选择匹配集合中所有索引值小于给定index参数的元素。):

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style>
</style>
</head> <body>
<table border="1">
<tr>
<td>TD #0</td>
<td>TD #1</td>
<td>TD #2</td>
</tr>
<tr>
<td>TD #3</td>
<td>TD #4</td>
<td>TD #5</td>
</tr>
<tr>
<td>TD #6</td>
<td>TD #7</td>
<td>TD #8</td>
</tr>
</table> <script>
$("document").ready(function() {
$("td:lt(4)").css("color", "red");
});
</script>
</body>
</html>

  输出结果:

  举例5(first() 方法,选取首个 <div> 元素内部的第一个 <p> 元素,last() 方法选择最后一个 <div> 元素中的最后一个 <p> 元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p").first().css("background-color", "red"); <!--将所有匹配元素设置background-color值-->
$("p").last().css({"background-color": "yellow"}); <!--设置多个css属性时建议使用此方法,虽然此处只有一个属性-->
});
</script> </head> <body class="siblings">
<h1>欢迎来到我的主页</h1>
<div>
<p>这是 div 中的一个段落。</p>
</div> <div>
<p>这是 div 中的另一个段落。</p>
</div> <p>这也是段落。</p> </body>
</html>

  输出结果:

  举例2(eq() 方法,索引号从 0 开始,因此首个元素的索引号是 0 而不是 1。下面的例子选取第二个 <p> 元素(索引号 1)):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p").eq(1).css("background-color", "yellow");
});
</script> </head> <body class="siblings"> <h1>欢迎来到我的主页</h1>
<p>我是唐老鸭 (index 0)。</p>
<p>唐老鸭 (index 1)。</p>
<p>我住在 Duckburg (index 2)。</p>
<p>我最好的朋友是米老鼠 (index 3)。</p> </body>
</html>

  输出结果:

  举例6(filter() 方法,下面的例子返回带有类名 "intro"(class="intro") 的所有 <p> 元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p").filter("p.intro").css("background-color","yellow");
<!--等价于-->
<!--$("p").filter(".intro").css("background-color","yellow");-->
});
</script> </head> <body class="siblings">
<h1>欢迎来到我的主页</h1>
<p>我是唐老鸭。</p>
<p class="intro">我住在 Duckburg。</p>
<p class="intro">我爱 Duckburg。</p>
<p>我最好的朋友是 Mickey。</p> </body>
</html>

  输出结果:

  举例7(not() 方法,下面的例子返回不带有类名 "intro" 的所有 <p> 元素):

 <!DOCTYPE html>
<html>
<head>
<!--<meta charset="utf-8">-->
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <!--引用jQuery库,src可以直接指向本地下载的jQery库-->
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">-->
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("p").not("p.intro").css("background-color","yellow");
<!--等价于-->
<!--$("p").not(".intro").css("background-color","yellow");-->
});
</script> </head> <body class="siblings">
<h1>欢迎来到我的主页</h1>
<p>我是唐老鸭。</p>
<p class="intro">我住在 Duckburg。</p>
<p class="intro">我爱 Duckburg。</p>
<p>我最好的朋友是 Mickey。</p> </body>
</html>

  输出结果:

7、事件方法

  下面是 jQuery 中事件方法的一些例子:

Event 函数 绑定函数至
$(document).ready(function) 将函数绑定到文档的就绪事件(当文档完成加载时)
$(selector).click(function) 触发或将函数绑定到被选元素的点击事件
$(selector).dblclick(function) 触发或将函数绑定到被选元素的双击事件
$(selector).focus(function) 触发或将函数绑定到被选元素的获得焦点事件
$(selector).mouseover(function)                                              触发或将函数绑定到被选元素的鼠标悬停事件                                                                 

  事件方法会触发匹配元素的事件,或将函数绑定到所有匹配元素的某个事件。

  概述:

方法 描述
bind() 向匹配元素附加一个或更多事件处理器
blur() 触发、或将函数绑定到指定元素的 blur 事件
change() 触发、或将函数绑定到指定元素的 change 事件
click() 触发、或将函数绑定到指定元素的 click 事件
dblclick() 触发、或将函数绑定到指定元素的 double click 事件
delegate() 向匹配元素的当前或未来的子元素附加一个或多个事件处理器
die() 移除所有通过 live() 函数添加的事件处理程序。
error() 触发、或将函数绑定到指定元素的 error 事件
event.isDefaultPrevented() 返回 event 对象上是否调用了 event.preventDefault()。
event.pageX 相对于文档左边缘的鼠标位置。
event.pageY 相对于文档上边缘的鼠标位置。
event.preventDefault() 阻止事件的默认动作。
event.result 包含由被指定事件触发的事件处理器返回的最后一个值。
event.target 触发该事件的 DOM 元素。
event.timeStamp 该属性返回从 1970 年 1 月 1 日到事件发生时的毫秒数。
event.type 描述事件的类型。
event.which 指示按了哪个键或按钮。
focus() 触发、或将函数绑定到指定元素的 focus 事件
keydown() 触发、或将函数绑定到指定元素的 key down 事件
keypress() 触发、或将函数绑定到指定元素的 key press 事件
keyup() 触发、或将函数绑定到指定元素的 key up 事件
live() 为当前或未来的匹配元素添加一个或多个事件处理器
load() 触发、或将函数绑定到指定元素的 load 事件
mousedown() 触发、或将函数绑定到指定元素的 mouse down 事件
mouseenter() 触发、或将函数绑定到指定元素的 mouse enter 事件
mouseleave() 触发、或将函数绑定到指定元素的 mouse leave 事件
mousemove() 触发、或将函数绑定到指定元素的 mouse move 事件
mouseout() 触发、或将函数绑定到指定元素的 mouse out 事件
mouseover() 触发、或将函数绑定到指定元素的 mouse over 事件
mouseup() 触发、或将函数绑定到指定元素的 mouse up 事件
one() 向匹配元素添加事件处理器。每个元素只能触发一次该处理器。
ready() 文档就绪事件(当 HTML 文档就绪可用时)
resize() 触发、或将函数绑定到指定元素的 resize 事件
scroll() 触发、或将函数绑定到指定元素的 scroll 事件
select() 触发、或将函数绑定到指定元素的 select 事件
submit() 触发、或将函数绑定到指定元素的 submit 事件
toggle() 绑定两个或多个事件处理器函数,当发生轮流的 click 事件时执行。
trigger() 所有匹配元素的指定事件
triggerHandler() 第一个被匹配元素的指定事件
unbind() 从匹配元素移除一个被添加的事件处理器
undelegate() 从匹配元素移除一个被添加的事件处理器,现在或将来
unload()                                                            触发、或将函数绑定到指定元素的 unload 事件                                                                                                                                           

  详细说明:

方法 描述
bind()

(bind:绑定)向匹配元素附加一个或更多事件处理器。bind() 方法为被选元素添加一个或多个事件处理程序,并规定事件发生时运行的函数。

$(selector).bind(event,data,function)

  • event:必需。规定添加到元素的一个或多个事件。由空格分隔多个事件。必须是有效的事件。
  • data:可选。规定传递到函数的额外数据。
  • function:必需。规定当事件发生时运行的函数。

$(selector).bind({event:function, event:function, ...})

  • {event:function, event:function, ...}:必需。规定事件映射,其中包含一个或多个添加到元素的事件,以及当事件发生时运行的函数。
blur()

(blur:模糊不清)触发、或将函数绑定到指定元素的 blur 事件(与focus()获得焦点相对应)。当元素失去焦点时发生 blur 事件。blur() 函数触发 blur 事件,或者如果设置了 function 参数,该函数也可规定当发生 blur 事件时执行的代码。

触发blur事件(触发被选元素的 blur 事件):$(selector).blur()

将函数绑定到 blur 事件,规定当被选元素的 blur 事件发生时运行的函数:$(selector).blur(function)

  • function:可选,规定当 blur 事件发生时运行的函数。
change()

触发、或将函数绑定到指定元素的 change 事件。当元素的值(value)发生改变时,会发生 change 事件。该事件仅适用于文本域(text field),以及 textarea 和 select 元素。change() 函数触发 change 事件,或规定当发生 change 事件时运行的函数。

触发 change 事件,触发被选元素的 change 事件:$(selector).change()

将函数绑定到 change 事件,规定当被选元素的 change 事件发生时运行的函数:$(selector).change(function)

  • function:可选,规定当 change 事件发生时运行的函数。
click() 触发、或将函数绑定到指定元素的 click 事件。当点击元素时,会发生 click 事件。当鼠标指针停留在元素上方,然后按下并松开鼠标左键时,就会发生一次 click。click() 方法触发 click 事件,或规定当发生 click 事件时运行的函数。

触发 click 事件:$(selector).click()

将函数绑定到 click 事件:$(selector).click(function)

  • function:可选,规定当发生 click 事件时运行的函数。
dblclick() 触发、或将函数绑定到指定元素的 double click 事件。当双击元素时,会发生 dblclick 事件。当鼠标指针停留在元素上方,然后按下并松开鼠标左键时,就会发生一次 click。在很短的时间内发生两次 click,即是一次 double click 事件。dblclick() 方法触发 dblclick 事件,或规定当发生 dblclick 事件时运行的函数。

提示:如果把 dblclick 和 click 事件应用于同一元素,可能会产生问题。

触发 dblclick 事件:$(selector).dblclick()

将函数绑定到 dblclick 事件:$(selector).dblclick(function)

  • function:可选,规定当发生 click 事件时运行的函数。
delegate() 向匹配元素的当前或未来的子元素附加一个或多个事件处理器。delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。使用 delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。

定义与用法:$(selector).delegate(childSelector,event,data,function)

  • childSelector:必需。规定要附加事件处理程序的一个或多个子元素。
  • event:必需。规定附加到元素的一个或多个事件。由空格分隔多个事件值。必须是有效的事件。
  • data:可选。规定传递到函数的额外数据。
  • function:必需。规定当事件发生时运行的函数。
die() 移除所有通过 live() 函数添加的事件处理程序。die() 方法移除所有通过 live() 方法向指定元素添加的一个或多个事件处理程序。

定义与用法:$(selector).die(event,function)

  • event:必需。规定要移除的一个或多个事件处理程序。由空格分隔多个事件值。必须是有效的事件。
  • function:可选。规定要移除的特定函数。
error() 触发、或将函数绑定到指定元素的 error 事件。当元素遇到错误(没有正确载入)时,发生 error 事件。error() 方法触发 error 事件,或规定当发生 error 事件时运行的函数。

提示:该方法是 bind('error', handler) 的简写方式。

触发 error 事件:$(selector).error()

将函数绑定到 error 事件:$(selector).error(function)

  • function:可选,规定当发生 click 事件时运行的函数。
event.isDefaultPrevented() 返回 event 对象上是否调用了 event.preventDefault()。isDefaultPrevented() 方法返回指定的 event 对象上是否调用了 preventDefault() 方法。

定义与用法:event.isDefaultPrevented()

  • event:必需。规定需要检查的事件。这个 event 参数来自事件绑定函数。
// 防止链接打开 URL,并声明来自 isDefaultPrevented() 的结果:
$("a").click(function(event){
event.preventDefault();
alert("Default prevented: " + event.isDefaultPrevented());
});

  输出结果:略。

event.pageX

相对于文档左边缘的鼠标位置。pageX() 属性是鼠标指针的位置,相对于文档的左边缘。

定义与用法:event.pageX

  • event:必需。规定要使用的事件。这个 event 参数来自事件绑定函数。
// 实时显示鼠标指针的位置
$(document).mousemove(function(e){
$("span").text("X: " + e.pageX + ", Y: " + e.pageY);
});

  输出结果:略。

event.pageY 相对于文档上边缘的鼠标位置。pageY() 属性是鼠标指针的位置,相对于文档的上边缘。

定义与用法:event.pageY

  • event:必需。规定要使用的事件。这个 event 参数来自事件绑定函数。
event.preventDefault()

阻止事件的默认动作。preventDefault() 方法阻止元素发生默认的行为(例如,当点击提交按钮时阻止对表单的提交)。

定义与语法:event.preventDefault()

  • event:必需。规定要使用的事件。这个 event 参数来自事件绑定函数。
event.result

包含由被指定事件触发的事件处理器返回的最后一个值。result 属性包含由被指定事件触发的事件处理器返回的最后一个值,除非这个值未定义。
定义与语法:event.result

  • event:必需。规定返回的最后一个值来自哪个事件。这个 event 参数来自事件绑定函数。
// 显示最后一次点击事件返回的结果
$(document).ready(function(){
$("button").click(function(e) {
return ("最后一次点击的鼠标位置是: X" +e.pageX + ", Y" + e.pageY);
});
$("button").click(function(e) {
$("p").html(e.result);
});
});

  输出结果:略。

event.target

触发该事件的 DOM 元素。target 属性规定哪个 DOM 元素触发了该事件。

定义与语法:event.target

  • event:必需。规定返回的最后一个值来自哪个事件。这个 event 参数来自事件绑定函数。
// 显示哪个 DOM 元素触发了事件
$(document).ready(function(){
$("p, button, h1, h2").click(function(event){
$("div").html("点击事件由一个 " + event.target.nodeName + " 元素触发");
});
});

  输出结果:略。

event.timeStamp

该属性返回从 1970 年 1 月 1 日到事件发生时的毫秒数。timeStamp 属性包含从 1970 年 1 月 1 日到事件被触发时的毫秒数。

定义与语法:event.timeStamp

  • event:必需。规定返回的最后一个值来自哪个事件。这个 event 参数来自事件绑定函数。
// 显示出当对按钮元素的点击事件发生时的时间戳
$(document).ready(function(){
$("button").click(function(e){
$("span").text(e.timeStamp);
});
});

  输出结果:略。

event.type

描述事件的类型。type 属性描述触发哪种事件类型。

定义与语法:event.type

  • event:必需。规定返回的最后一个值来自哪个事件。这个 event 参数来自事件绑定函数。
// 显示触发了哪种类型的事件
$(document).ready(function(){
$("p").bind('click dblclick mouseover mouseout',function(event){
$("div").html("事件:" + event.type);
});
});

  输出结果:略。

event.which

指示按了哪个键或按钮。which 属性指示按了哪个键或按钮。

定义与语法:event.which

  • event:必需。规定返回的最后一个值来自哪个事件。这个 event 参数来自事件绑定函数。
// 显示按了哪个键
$(document).ready(function(){
$("input").keydown(function(event){
$("div").html("Key: " + event.which);
});
});

  输出结果:略。

focus()

触发、或将函数绑定到指定元素的 focus 事件。当元素获得焦点时,发生 focus 事件。当通过鼠标点击选中元素或通过 tab 键定位到元素时,该元素就会获得焦点。focus() 方法触发 focus 事件,或规定当发生 focus 事件时运行的函数。

触发 focus 事件:$(selector).focus()

将函数绑定到 focus 事件:$(selector).focus(function)

  • function:可选。规定当发生 focus 事件时运行的函数。
// 当输入框获得焦点时,改变它的背景色
$(document).ready(function(){
$("input").focus(function(){
$("input").css("background-color","#FFFFCC");
});
$("input").blur(function(){
$("input").css("background-color","#D6D6FF");
});
});

  输出结果:略。

keydown()

触发、或将函数绑定到指定元素的 key down 事件。完整的 key press 过程分为两个部分:1. 按键被按下;2. 按键被松开。当按钮被按下时,发生 keydown 事件。keydown() 方法触发 keydown 事件,或规定当发生 keydown 事件时运行的函数。

注释:如果在文档元素上进行设置,则无论元素是否获得焦点,该事件都会发生。

提示:请使用 .which 属性来确定按下了哪个按键。

触发 focus 事件:$(selector).keydown()

将函数绑定到 focus 事件:$(selector).keydown(function)

  • function:可选。规定当发生 keydown 事件时运行的函数。
// 当按下按键时,改变文本域的颜色
$(document).ready(function(){
$("input").keydown(function(){
$("input").css("background-color","#FFFFCC");
});
$("input").keyup(function(){
$("input").css("background-color","#D6D6FF");
});
});

  输出结果:略。

  举例2(获取键盘的键值):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style> </style>
</head> <body> <script>
$(document).ready(function() {
$(this).keydown(function(event) {
alert("keydown, keyValue: " + event.keyCode);
});
});
</script>
</body>
</html>

  输出结果:略。

keypress()

触发、或将函数绑定到指定元素的 key press 事件。keypress 事件与 keydown 事件类似。当按钮被按下时,会发生该事件。它发生在当前获得焦点的元素上。不过,与 keydown 事件不同,每插入一个字符,就会发生 keypress 事件。keypress() 方法触发 keypress 事件,或规定当发生 keypress 事件时运行的函数。

注释:如果在文档元素上进行设置,则无论元素是否获得焦点,该事件都会发生。

触发 keypress 事件:$(selector).keypress()

将函数绑定到 keypress 事件:$(selector).keypress(function)

  • function:可选。规定当发生 keypress 事件时运行的函数。
// 计算在输入域中的按键次数
i=0;
$(document).ready(function(){
$("input").keypress(function(){
$("span").text(i+=1);
});
});

  输出结果:略。

keyup() 触发、或将函数绑定到指定元素的 key up 事件。触发、或将函数绑定到指定元素的 key down 事件。完整的 key press 过程分为两个部分:1. 按键被按下;2. 按键被松开。当按钮被松开时,发生 keyup 事件。它发生在当前获得焦点的元素上。keydown() 方法触发 keyup 事件,或规定当发生 keyup 事件时运行的函数。

注释:如果在文档元素上进行设置,则无论元素是否获得焦点,该事件都会发生。

提示:请使用 .which 属性来确定按下了哪个按键。

触发 focus 事件:$(selector).keyup()

将函数绑定到 focus 事件:$(selector).keyup(function)

  • function:可选。规定当发生 keyup事件时运行的函数。

注意:keyup()只有在keydown()和keypress()都没有被注册的情况下才会被触发。

  举例:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta http-equiv="Content-Language" content="zh-cn" />
<title>My test page</title> <script src="jquery-3.3.1.js"></script>
<style> </style>
</head> <body> <script>
$(document).ready(function() {
// 情形1(屏蔽情形2的代码内容):在同时注册了keydown、keypress、keyup时,只会keydown、keypress生效,keyup则不会生效
/*
$(this).keydown(function(event) {
alert("keydown");
});
$(this).keypress(function(event) {
alert("keypress");
});
$(this).keyup(function(event) {
alert("keyup");
});
*/
// 情形2(屏蔽情形1的代码内容):在同时注册了keydown、keypress、keyup时,只会keydown、keypress生效,keyup则不会生效
$(this).keyup(function(event) {
alert("keyup");
});
});
</script>
</body>
</html>

  输出结果:略。

live()

为当前或未来的匹配元素添加一个或多个事件处理器。live() 方法为被选元素附加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。通过 live() 方法附加的事件处理程序适用于匹配选择器的当前及未来的元素(比如由脚本创建的新元素)。

定义与用法:$(selector).live(event,data,function)

  • event:必需。规定附加到元素的一个或多个事件。由空格分隔多个事件。必须是有效的事件。
  • data:可选。规定传递到该函数的额外数据。
  • function:必需。规定当事件发生时运行的函数。
// 当点击按钮时,隐藏或显示 p 元素
$(document).ready(function(){
$("button").live("click",function(){
$("p").slideToggle();
});
});

  输出结果:略。

load()

触发、或将函数绑定到指定元素的 load 事件。当指定的元素(及子元素)已加载时,会发生 load() 事件。该事件适用于任何带有 URL 的元素(比如图像、脚本、框架、内联框架)。根据不同的浏览器(Firefox 和 IE),如果图像已被缓存,则也许不会触发 load 事件。

注释:还存在一个名为 load() 的 jQuery Ajax 方法,根据不同的参数而定。

定义与用法:$(selector).load(function)

  • function:必需。规定当指定元素加载完成时运行的函数。
// 当图像加载时,改变 div 元素的文本
$(document).ready(function(){
$("img").load(function(){
$("div").text("图像已加载");
});
});

  输出结果:略。

mousedown()

触发、或将函数绑定到指定元素的 mouse down 事件。当鼠标指针移动到元素上方,并按下鼠标按键时,会发生 mousedown 事件。与 click 事件不同,mousedown 事件仅需要按键被按下,而不需要松开即可发生。mousedown() 方法触发 mousedown 事件,或规定当发生 mousedown 事件时运行的函数。

触发 mousedown 事件:$(selector).mousedown()

将函数绑定到 mousedown 事件:$(selector).mousedown(function)

  • function:可选。规定当发生 mousedown 事件时运行的函数。
// 当按下鼠标按钮时,隐藏或显示元素
$(document).ready(function(){
$("button").mousedown(function(){
$("p").slideToggle();
});
});

  输出结果:略。

mouseenter()

触发、或将函数绑定到指定元素的 mouse enter 事件。当鼠标指针穿过元素时,会发生 mouseenter 事件。该事件大多数时候会与 mouseleave 事件一起使用。mouseenter() 方法触发 mouseenter 事件,或规定当发生 mouseenter 事件时运行的函数。

注释:与 mouseover 事件不同,只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件。如果鼠标指针穿过任何子元素,同样会触发 mouseover 事件。请看下面例子的演示。

亲自试一试:mouseenter 与 mouseover 的不同

触发 mouseenter 事件:$(selector).mouseenter()

将函数绑定到 mouseenter 事件:$(selector).mouseenter(function)

  • function:可选。规定当发生 mouseenter 事件时运行的函数。
// 当鼠标指针进入(穿过)元素时,改变元素的背景色
$(document).ready(function(){
$("p").mouseenter(function(){
$("p").css("background-color","yellow");
});
$("p").mouseleave(function(){
$("p").css("background-color","#E9E9E4");
});
});

  输出结果:略。

mouseleave()

触发、或将函数绑定到指定元素的 mouse leave 事件。当鼠标指针离开元素时,会发生 mouseleave 事件。该事件大多数时候会与 mouseenter 事件一起使用。mouseleave() 方法触发 mouseleave 事件,或规定当发生 mouseleave 事件时运行的函数。

注释:与 mouseout 事件不同,只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。如果鼠标指针离开任何子元素,同样会触发 mouseout 事件。请看下面例子的演示。
亲自试一试:mouseleave 与 mouseout 的不同

触发 mouseleave 事件:$(selector).mouseleave()

将函数绑定到 mouseleave 事件:$(selector).mouseleave(function)

  • function:可选。规定当发生 mouseleave 事件时运行的函数。
mousemove()

触发、或将函数绑定到指定元素的 mouse move 事件。当鼠标指针在指定的元素中移动时,就会发生 mousemove 事件。mousemove() 方法触发 mousemove 事件,或规定当发生 mousemove 事件时运行的函数。

注意:用户把鼠标移动一个像素,就会发生一次 mousemove 事件。处理所有 mousemove 事件会耗费系统资源。请谨慎使用该事件。

触发 mousemove 事件:$(selector).mousemove()

将函数绑定到 mousemove 事件:$(selector).mousemove(function)

  • function:可选。规定当发生 mousemove 事件时运行的函数。
// 获得鼠标指针在页面中的位置
$(document).ready(function(){
$(document).mousemove(function(e){
$("span").text(e.pageX + ", " + e.pageY);
});
});

  输出结果:略。

mouseout()

触发、或将函数绑定到指定元素的 mouse out 事件。当鼠标指针从元素上移开时,发生 mouseout 事件。该事件大多数时候会与 mouseover 事件一起使用。mouseout() 方法触发 mouseout 事件,或规定当发生 mouseout 事件时运行的函数。

注释:与 mouseleave 事件不同,不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。请看下面例子的演示。

亲自试一试:mouseleave 与 mouseout 的不同

触发 mouseout 事件:$(selector).mouseout()

将函数绑定到 mouseout 事件:$(selector).mouseout(function)

  • function:可选。规定当发生 mouseout 事件时运行的函数。
// 当鼠标从元素上移开时,改变元素的背景色
$(document).ready(function(){
$("p").mouseover(function(){
$("p").css("background-color","yellow");
});
$("p").mouseout(function(){
$("p").css("background-color","#E9E9E4");
});
});

  输出结果:略。

mouseover()

触发、或将函数绑定到指定元素的 mouse over 事件。当鼠标指针位于元素上方时,会发生 mouseover 事件。该事件大多数时候会与 mouseout 事件一起使用。mouseover() 方法触发 mouseover 事件,或规定当发生 mouseover 事件时运行的函数。

注释:与 mouseenter 事件不同,不论鼠标指针穿过被选元素或其子元素,都会触发 mouseover 事件。只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件。请看下面例子的演示。

亲自试一试:mouseenter 与 mouseover 的不同

触发 mouseover 事件:$(selector).mouseover()

将函数绑定到 mouseover 事件:$(selector).mouseover(function)

  • function:可选。规定当发生 mouseover 事件时运行的函数。
mouseup()

触发、或将函数绑定到指定元素的 mouse up 事件。当在元素上放松鼠标按钮时,会发生 mouseup 事件。与 click 事件不同,mouseup 事件仅需要放松按钮。当鼠标指针位于元素上方时,放松鼠标按钮就会触发该事件。mouseup() 方法触发 mouseup 事件,或规定当发生 mouseup 事件时运行的函数。

触发 mouseup 事件:$(selector).mouseup()

将函数绑定到 mouseup 事件:$(selector).mouseup(function)

  • function:可选。规定当发生 mouseup 事件时运行的函数。
// 当松开鼠标按钮时,隐藏或显示元素
$(document).ready(function(){
$("button").mouseup(function(){
$("p").slideToggle();
});
});

  输出结果:略。

one()

向匹配元素添加事件处理器。每个元素只能触发一次该处理器。one() 方法为被选元素附加一个或多个事件处理程序,并规定当事件发生时运行的函数。当使用 one() 方法时,每个元素只能运行一次事件处理器函数。

定义与用法:$(selector).one(event,data,function)

  • event:必需。规定添加到元素的一个或多个事件。由空格分隔多个事件。必须是有效的事件。
  • data:可选。规定传递到函数的额外数据。
  • function:必需。规定当事件发生时运行的函数。
// 当点击 p 元素时,增加该元素的文本大小
$(document).ready(function(){
$("p").one("click",function(){
$(this).animate({fontSize:"+=6px"});
});
});

  输出结果:略。

ready()

文档就绪事件(当 HTML 文档就绪可用时)。当 DOM(文档对象模型) 已经加载,并且页面(包括图像)已经完全呈现时,会发生 ready 事件。由于该事件在文档就绪后发生,因此把所有其他的 jQuery 事件和函数置于该事件中是非常好的做法。正如上面的例子中那样。

ready() 函数规定当 ready 事件发生时执行的代码。ready() 函数仅能用于当前文档,因此无需选择器。

允许使用以下三种语法:

语法 1:$(document).ready(function)

语法 2:$().ready(function)

语法 3:$(function)

  • function:必需。规定当文档加载后要运行的函数。

提示:ready() 函数不应与 <body onload=""> 一起使用。

resize()

触发、或将函数绑定到指定元素的 resize 事件。当调整浏览器窗口的大小时,发生 resize 事件。resize() 方法触发 resize 事件,或规定当发生 resize 事件时运行的函数。

触发 resize 事件:$(selector).resize()

将函数绑定到 resize 事件:$(selector).resize(function)

  • function:可选。规定当发生 resize 事件时运行的函数。
// 对浏览器窗口调整大小进行计数
$(document).ready(function(){
$(window).resize(function() {
$("span").text(x+=1);
});
});

  输出结果:略。

scroll()

触发、或将函数绑定到指定元素的 scroll 事件。当用户滚动指定的元素时,会发生 scroll 事件。scroll 事件适用于所有可滚动的元素和 window 对象(浏览器窗口)。scroll() 方法触发 scroll 事件,或规定当发生 scroll 事件时运行的函数。

触发 scroll 事件:$(selector).scroll()

将函数绑定到 scroll 事件:$(selector).scroll(function)

  • function:可选。规定当发生 scroll 事件时运行的函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
x=0;
$(document).ready(function(){
$("div").scroll(function() {
  $("span").text(x+=1);
});
});
</script>
</head> <body>
<!--对元素滚动的次数进行计数-->
<p>请试着滚动 DIV 中的文本:</p>
<div style="width:200px;height:100px;overflow:scroll;">text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text.
<br /><br />
text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text. text.</div>
<p>滚动了 <span>0</span> 次。</p>
</body>
</html>

  输出结果:略。

select()

触发、或将函数绑定到指定元素的 select 事件。当 textarea 或文本类型的 input 元素中的文本被选择时,会发生 select 事件。select() 方法触发 select 事件,或规定当发生 select 事件时运行的函数。

触发 select 事件:$(selector).select()

将函数绑定到 select 事件:$(selector).select(function)

  • function:可选。规定当发生 select 事件时运行的函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("input").select(function(){
    $("input").after(" Text marked!");
  });
});
</script>
</head> <body>
<!--在文本域后添加文本,以显示出提示文本-->
<input type="text" name="FirstName" value="Hello World" />
<p>请试着选取输入域中的文本,看看会发生什么。</p>
</body>
</html>

  输出结果:略。

submit()

触发、或将函数绑定到指定元素的 submit 事件。当提交表单时,会发生 submit 事件。该事件只适用于表单元素。submit() 方法触发 submit 事件,或规定当发生 submit 事件时运行的函数。

触发 submit 事件:$(selector).submit()

将函数绑定到 submit 事件:$(selector).submit(function)

  • function:可选。规定当发生 submit 事件时运行的函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(e){
alert("Submitted");
});
});
</script>
</head> <body>
<!--当提交表单时,显示警告框-->
<form name="input" action="" method="get">
First name:
<input type="text" name="FirstName" value="Mickey" size="20">
<br />Last name:
<input type="text" name="LastName" value="Mouse" size="20">
<br />
<input type="submit" value="Submit">
</form>
</body>
</html>

  输出结果:略。

toggle()

绑定两个或多个事件处理器函数,当发生轮流的 click 事件时执行。toggle() 方法用于绑定两个或多个事件处理器函数,以响应被选元素的轮流的 click 事件。该方法也可用于切换被选元素的 hide() 与 show()方法。

向 Toggle 事件绑定两个或更多函数:$(selector).toggle(function1(),function2(),functionN(),...)

当指定元素被点击时,在两个或多个函数之间轮流切换。

如果规定了两个以上的函数,则 toggle() 方法将切换所有函数。例如,如果存在三个函数,则第一次点击将调用第一个函数,第二次点击调用第二个函数,第三次点击调用第三个函数。第四次点击再次调用第一个函数,以此类推。

  • function1():必需。规定当元素在每偶数次被点击时要运行的函数。
  • function2():必需。规定当元素在每奇数次被点击时要运行的函数。
  • functionN(),...:可选。规定需要切换的其他函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").toggle(function(){
$("body").css("background-color","green");},
function(){
$("body").css("background-color","red");},
function(){
$("body").css("background-color","yellow");}
);
});
</script>
</head> <body>
<button>请点击这里,来切换不同的背景颜色</button>
</body>
</html>

  输出结果:略。

切换 Hide() 和 Show():$(selector).toggle(speed,callback)

检查每个元素是否可见。

如果元素已隐藏,则运行 show()。如果元素可见,则元素 hide()。这样就可以创造切换效果。

  • speed:可选。规定 hide/show 效果的速度。默认是 "0"。可能的值:毫秒(比如 1500)、"slow"、"normal"、"fast"
  • callback:可选。当 toggle() 方法完成时执行的函数。

如需学习更多有关 callback 的知识,请访问Callback 函数教程

$(document).ready(function(){
$(".btn1").click(function(){
$("p").toggle(1000);
});
});

显示或隐藏元素:$(selector).toggle(switch)

规定是否只显示或只隐藏所有匹配的元素。

  • switch:必需。布尔值,规定 toggle() 是否应只显示或只隐藏所有被选元素。true - 显示元素;false - 隐藏元素
$(document).ready(function(){
$(".btn1").click(function(){
$("p").toggle(true);
});
});
trigger()

所有匹配元素的指定事件。trigger() 方法触发被选元素的指定事件类型。

触发事件,规定被选元素要触发的事件:$(selector).trigger(event,[param1,param2,...])

  • event:必需。规定指定元素要触发的事件。可以使自定义事件(使用 bind() 函数来附加),或者任何标准事件。
  • [param1,param2,...]:可选。传递到事件处理程序的额外参数。额外的参数对自定义事件特别有用。

使用 Event 对象来触发事件,规定使用事件对象的被选元素要触发的事件:$(selector).trigger(eventObj)

  • eventObj:必需。规定事件发生时运行的函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").select(function(){
$("input").after("文本被选中!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
</script>
</head> <body>
<!--触发 input 元素的 select 事件-->
<input type="text" name="FirstName" value="Hello World" />
<br />
<button>激活 input 域的 select 事件</button>
</body>
</html>

  输出结果:略。

triggerHandler()

第一个被匹配元素的指定事件。

triggerHandler() 方法触发被选元素的指定事件类型。但不会执行浏览器默认动作,也不会产生事件冒泡。
triggerHandler() 方法与 trigger() 方法类似。不同的是它不会触发事件(比如表单提交)的默认行为,而且只影响第一个匹配元素。

与 trigger() 方法相比的不同之处

  • 它不会引起事件(比如表单提交)的默认行为
  • .trigger() 会操作 jQuery 对象匹配的所有元素,而 .triggerHandler() 只影响第一个匹配元素。
  • 由 .triggerHandler() 创建的事件不会在 DOM 树中冒泡;如果目标元素不直接处理它们,则不会发生任何事情。
  • 该方法的返回的是事件处理函数的返回值,而不是具有可链性的 jQuery 对象。此外,如果没有处理程序被触发,则这个方法返回 undefined。

触发事件,规定被选元素要触发的事件:$(selector).triggerHandler(event,[param1,param2,...])

  • event:必需。规定指定元素要触发的事件。
  • [param1,param2,...]:可选。传递到事件处理程序的额外参数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").select(function(){
$("input").after("发生 Input select 事件!");
});
$("button").click(function(){
$("input").triggerHandler("select");
});
});
</script>
</head> <body>
<!--触发 input 元素的 select 事件-->
<input type="text" name="FirstName" value="Hello World" />
<br />
<button>激活 input 域的 select 事件</button>
<p>请注意,与 trigger() 方法不同,triggerHandler() 方法不会引起所发生事件的默认行为(文本不会被选中)。</p>
</body>
</html>

  输出结果:略。

unbind()

从匹配元素移除一个被添加的事件处理器。

unbind() 方法移除被选元素的事件处理程序。该方法能够移除所有的或被选的事件处理程序,或者当事件发生时终止指定函数的运行。
ubind() 适用于任何通过 jQuery 附加的事件处理程序。

取消绑定元素的事件处理程序和函数:$(selector).unbind(event,function)
规定从指定元素上删除的一个或多个事件处理程序。
如果没有规定参数,unbind() 方法会删除指定元素的所有事件处理程序。

  • event:可选。规定删除元素的一个或多个事件,由空格分隔多个事件值。如果只规定了该参数,则会删除绑定到指定事件的所有函数。
  • function:可选。规定从元素的指定事件取消绑定的函数名。

使用 Event 对象来取消绑定事件处理程序:$(selector).unbind(eventObj)
规定要删除的事件对象。用于对自身内部的事件取消绑定(比如当事件已被触发一定次数之后,删除事件处理程序)。
如果未规定参数,则 unbind() 方法会删除指定元素的所有事件处理程序。

  • eventObj:可选。规定要使用的事件对象。这个 eventObj 参数来自事件绑定函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).slideToggle();
});
$("button").click(function(){
$("p").unbind();
});
});
</script>
</head> <body>
<!--移除所有 p 元素的事件处理器-->
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<p>点击任何段落可以令其消失。包括本段落。</p>
<button>删除 p 元素的事件处理器</button>
</body>
</html>

  输出结果:略。

undelegate()

从匹配元素移除一个被添加的事件处理器,现在或将来。undelegate() 方法删除由 delegate() 方法添加的一个或多个事件处理程序。

定义与用法:$(selector).undelegate(selector,event,function)

  • selector:可选。规定需要删除事件处理程序的选择器。
  • event:可选。规定需要删除处理函数的一个或多个事件类型。
  • function:可选。规定要删除的具体事件处理函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("body").delegate("p","click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("body").undelegate();
});
});
</script>
</head> <body>
<!--从所有元素删除由 delegate() 方法添加的所有事件处理器-->
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<p>点击任何段落可以令其消失。包括本段落。</p>
<button>从所有元素删除由 delegate() 方法添加的事件处理器</button>
</body>
</html>

  输出结果:略。

unload()                          

触发、或将函数绑定到指定元素的 unload 事件。

当用户离开页面时,会发生 unload 事件。

具体来说,当发生以下情况时,会发出 unload 事件:

  • 点击某个离开页面的链接
  • 在地址栏中键入了新的 URL
  • 使用前进或后退按钮
  • 关闭浏览器
  • 重新加载页面
  • unload() 方法将事件处理程序绑定到 unload 事件。

unload() 方法只应用于 window 对象。

定义与用法:event.unload(function)

  • function:必需。规定当触发 unload 事件时运行的函数。
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).unload(function(){
alert("再见!");
});
});
</script>
</head> <body>
<!--当用户点击链接离开本页时,弹出一个消息框-->
<p>当您点击 <a href="http://w3school.com.cn">这个链接</a> 时,或者关闭窗口,会触发一个警告框。</p>
</body>
</html>

  输出结果:略。

8、JavaScript异步编程的四种方法

8.1 回调函数

8.2 事件监听

8.3 发布/订阅

8.4 Promises对象(jQuery Deferred对象的使用)

  举例:

 // jQuery的Deferred对象详解
// sel: true: done, false: fail
function foo(sel) {
return $.Deferred(function (def) {
if (sel) {
console.log("1.1 done initial");
def.resolve();
} else {
console.log("2.1 fail initial");
def.reject();
}
}).promise();
} foo(true).done(function () {
console.log("1.2 done");
}).fail(function () {
console.log("2.2 fail");
}); foo(false).done(function () {
console.log("1.2 done");
}).fail(function () {
console.log("2.2 fail");
});

  输出结果:略。

9、jQuery使用技巧

9.1 按钮的置灰、Loading、恢复等操作使用技巧

  举例:

 // 按钮的置灰、Loading、恢复等操作使用技巧

 /**
*
* @param {String} [message]
* @return {JQuery}
*/
$.fn.sdmShowLoading = function (message) {
var $btn = this;
var $text = $btn.find('.sdm_splitbutton_text');
if (!$btn.data('is-loading')) {
$btn.data('is-loading', true);
$btn.data('button-text', $text.text());
$btn.data('original-width', $btn[0].style.width);
$btn.attr("disabled", true).css({
'pointer-events': 'none',
'text-align': 'center',
'min-width': $btn.width()
});
}
$text.text(message || '');
$text.prepend('<i class="loading-indicator"></i>');
return this;
}; $.fn.sdmHideLoading = function () {
var $btn = this;
if ($btn.data('is-loading')) {
$btn[0].style.width = $btn.data('original-width');
$btn.find('.sdm_splitbutton_text').text($btn.data('button-text'));
$btn.attr("disabled", false).css({
'pointer-events': '',
'min-width': ''
});
$btn.data('is-loading', false);
}
return this;
}; $.fn.sdmDisable = function () {
return this.attr("disabled", true).css({
opacity: '0.7',
'pointer-events': 'none'
});
}; $.fn.sdmEnable = function () {
return this.attr("disabled", false).css({
opacity: '',
'pointer-events': ''
});
}; // 使用举例
$("#Submit").sdmShowLoading(); // 按钮出现刷新状态,Submit为 按钮组件ID
$("#Submit").sdmHideLoading(); // 按钮恢复使用状态,Submit为 按钮组件ID

  输出结果:略。

9.2 jQuery Utilities ($. 为 jQuery)

  见目录

Web开发——jQuery基础的更多相关文章

  1. Web开发——HTML基础

    文档资料参考: 参考:MDN官网 参考:http://www.runoob.com,W3School 参考:https://developer.mozilla.org/zh-CN/docs/Learn ...

  2. Web开发——HTML基础(图像、音频和视频内容)

    参考: 参考:HTML中的图像 参考:视频和音频内容 目录: 1.HTML中的图像 1.1 我们如何在网页上放置图像? (1)替代文字(alt) (2)宽度和高度 (3)图片标题 1.2 用图形和图形 ...

  3. web前端----jQuery基础语法

    一.jQuery基础1.为什么要用jquery? 写起来简单,省事,开发效率高,兼容性好2.什么是jQuery? jQuery是一个兼容多浏览器的JavaScript库(类似python里面的模块)3 ...

  4. Web开发——JavaScript基础

    参考学习: MDN JavaScript:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript ECMAScript 6入门(阮一峰):htt ...

  5. Web前端JQuery基础

    JQuery知识汇总 一.关于Jquery简介          jQuery是一个快速.简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(或JavaS ...

  6. 静态Web开发 JQuery

    伍章 JQuery 1节介绍JQuery和顶级对象 <<锋利的JQuery>>JQuery官网: http://jquery.com (下载jquery工具)JQuery在线A ...

  7. Web开发——HTML基础(HTML响应式Web设计 Bootstrap)

    参考: 参考:http://www.bootcss.com/ 目录: 1.什么是响应式 Web 设计? 2.创建自己的响应设计 3.使用 Bootstrap 1.什么是响应式 Web 设计? RWD ...

  8. Web开发——HTML基础(高级文本格式 列表/style)

    文档资料参考: 参考:https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_fo ...

  9. Web开发——CSS基础

    参考: 参考:http://css.doyoe.com/ 参考:http://www.w3school.com.cn/cssref/index.asp 参考:https://www.w3cschool ...

随机推荐

  1. 前端学习-jQuery-2

    老师的博客地址:https://www.cnblogs.com/yuanchenqi/articles/6070667.html day44 属性操作: ----------------------- ...

  2. thymeleaf th:href 多个参数传递格式

    今天在使用thymeleaf的th:href传递多个参数的时候困惑了.然后百度了一下,发现没有人注释说明怎么弄,然后自己google了一下,现在就标记一下,方便记录一下. th:href=" ...

  3. Atitti 互联网时代三大竞争战略 ——平台化战略 锚”战略、价值领先战略

    Atitti 互联网时代三大竞争战略 ——平台化战略 锚”战略.价值领先战略 美国著名管理学家迈克尔•波特在<竞争战略>一书中提出了集中化战略和差异化战略.成本领先战略三种基本竞争战略,从 ...

  4. SQL 对结果集进行分组排序过滤重复数据

    简单的表操作: select row_number() over(partition by A.gid order by A.gid ) as RowN, A.* from Fit_Order A 关 ...

  5. 【原创 Hadoop&Spark 动手实践 1】Hadoop2.7.3 安装部署实践

    目录: 第一部分:操作系统准备工作: 1. 安装部署CentOS7.3 1611 2. CentOS7软件安装(net-tools, wget, vim等) 3. 更新CentOS7的Yum源,更新软 ...

  6. VS2015 怎么安装RDLC报表模板?

    这几天刚好用到微软自带的RDLC报表,但是在VS2015张找了一圈也没找,难道是我VS版本 不支持,在网上查了下,有的人说VS2015社区版,企业版不支持,只有专业版支持,各说不一,想想不科学呀,微软 ...

  7. JQuery DataTables Selected Row

    获取单行选中的值 $('#MonitoringTypeTable tbody').on('click', 'tr', function () { if ($(this).hasClass('selec ...

  8. js 暂时存储 sessionStorge

    H5的storage有sessionstorage&localStorage,其中他们的共同特点是API相同 下面直接上代码,storage中的存储与删除: <!DOCTYPE html ...

  9. PHP 数组转XML 格式

    function buildXml( $data, $wrap= 'xml' ){ $str = "<{$wrap}>"; if( is_array( $data ) ...

  10. OpenGL——OpenCV与SOIL读取图片进行纹理贴图

    使用OpenCV读取图片代码如下 img = imread(m_fileName); if (img.empty()) { fprintf(stderr, "Can not load ima ...