参考学习:
- 参考W3School:jQuery 教程
- 参考:jQuery 参考手册
- 参考(常用):jQuery API
- 测试 JavaScript 框架库 - jQuery
- 测试 JavaScript 框架库 - Prototype
- jQuery库下载:https://jquery.com/
- Prototype库下载:http://prototypejs.org/
- 1、引用jQuery和Prototype
- 2、jQuery 语法
- 3、jQuery选择器
- 4、jQuery效果
- 5、jQuery HTML文档操作
- 6、jQuery遍历
- 6.1 祖先
- 6.2 后代/子元素过滤/层级
- 6.3 同胞
- 6.4 过滤(搜索特定的元素)/内容过滤
- 1)内容过滤
- 2)遍历——过滤
- 3)基础过滤
- 举例1(语法:$(":animated"),选择所有正在执行动画效果的元素)
- 举例2(:first Selector、:last Selector、:eq() Selector、:even Selector)
- 举例3(:focus Selector,选择当前获取焦点的元素)
- 举例4(:lt Selector,选择匹配集合中所有索引值小于给定index参数的元素)
- 举例5(first() 方法,选取首个 元素内部的第一个元素,last() 方法选择最后一个 元素中的最后一个元素)
- 举例6(eq() 方法,索引号从 0 开始,因此首个元素的索引号是 0 而不是 1。下面的例子选取第二个 元素(索引号 1))
- 举例6(filter() 方法,下面的例子返回带有类名 "intro"(class="intro") 的所有 元素)
- 举例7(not() 方法,下面的例子返回不带有类名 "intro" 的所有 元素)
- 7、事件方法
- 8、JavaScript异步编程的四种方法
- 9、jQuery使用技巧
- 9.2 jQuery Utilities ($. 为 jQuery)
1、引用jQuery和Prototype
1.1 引用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>-->
<script src="jquery-3.3.1.js">
</script>
</head>
<body>
</body>
</html>
1.2 引用Prototype
<!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>-->
<script src="prototype.js"> < !--已将prototype下载到本地中-->
</script>
</head>
<body>
</body>
</html>
1.3 jQuery描述
jQuery 是一个“写的更少,但做的更多”的轻量级 JavaScript 库。
主要的 jQuery 函数是 $() 函数(jQuery 函数)。如果您向该函数传递 DOM(Document Object Model) 对象,它会返回 jQuery 对象,带有向其添加的 jQuery 功能。
jQuery 允许您通过 CSS 选择器来选取元素。
在 JavaScript 中,您可以分配一个函数以处理窗口加载事件:
举例1(JavaScript 方式):
<!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>
上面代码的最后一行,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 的属性和方法。
举例2(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>-->
<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>
举例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>-->
<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>
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>-->
<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>
举例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>-->
<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>
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()):
<!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>-->
<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>
举例2($("#id_test").hide()):
<!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>-->
<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>
举例3($("p").hide()):
<!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>-->
<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>
举例4($(".class_test").hide()):
<!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>-->
<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>
2.2 jQuery 语法
jQuery 语法是为 HTML 元素的选取编制的,可以对元素执行某些操作。
基础语法是:$(selector).action()
- 美元符号定义 jQuery
- 选择符(selector)“查询”和“查找” HTML 元素
- jQuery 的 action() 执行对元素的操作
3、jQuery选择器
在前面的章节中,我们展示了一些有关如何选取 HTML 元素的实例。
关键点是学习 jQuery 选择器是如何准确地选取您希望应用效果的元素。
jQuery 元素选择器和属性选择器允许您通过标签名、属性名或内容对 HTML 元素进行选择。
选择器允许您对 HTML 元素组或单个元素进行操作。
在 HTML DOM 术语中:
选择器允许您对 DOM 元素组或单个 DOM 节点进行操作。
3.1 jQuery元素选择器
jQuery 使用 CSS 选择器来选取 HTML 元素。
- $("p"):选取 <p> 元素。
- $("p.intro"):选取所有 class="intro" 的 <p> 元素。
- $(".intro"):选取所有 class="intro" 的所有元素。
- $("p#demo"):选取所有 id="demo" 的 <p> 元素。
- $("#demo"):选取所有 id="demo" 的所有元素。
- $("#id1 #id2"):选取"#id1"元素下面的"#id2"的元素。
- $("#id1").find("#id2 #id3"):选取查询"#id1"元素下面的"#id2"下面的"#id3"元素("#id2"和"#id3"之间用空格隔开)。
- 选择多个元素,用逗号隔开。
举例:
<!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>
3.2 jQuery属性选择器
-
$("[attribute='value']":选择指定属性值等于给定字符串或者以该字符串为前缀(该字符串后跟一个连接符"-")的元素。
注意:引号是可选的,可以是一个不带引号的一个单词,或者带一个引号的字符串。// <p class="class_p1"></p> // <p id="id_p2"></p> $("p[class='class_p1']").html("第一个p标签"); $("p[id='id_p2']").html("第二个p标签");
-
$("[attribute*='value']":选择指定属性具有包含一个给定的子字符串的元素。(选择给定的属性是以包含某些值的元素)。
// <p class="class_p1"></p> // <p id="id_p2"></p> $("p[class*='class_']").html("第一个p标签"); $("p[id*='_p2']").html("第二个p标签");
-
$("[attribute~='value']":选择指定属性用空格分割的值中包含一个给定值的元素。
// <input name="man-news" /> // <input name="milk man" /> $("input[name~='man']").val("mr.man is in it");
-
$("[attribute!='value']":选择不存在指定属性,或者指定的属性值不等于给定值的元素。
// <p class="class_p1"></p> // <p id="id_p2"></p> // <p id="id_p3"></p> $("p[class!='class_p1']").html("除了第一个p标签的其它p标签值");
-
$("[attribute$='value']":选择指定属性是以给定值结尾的元素。这个比较是区分大小写的。
// <p class="class_p1"></p> // <p id="id_p2"></p> // <p id="id_p3"></p> $("p[id$='p2']").html("id为p2结尾的p标签");
-
$("[attribute^='value']":选择指定属性是以给定字符串开始的元素。
// <p class="class_p1"></p> // <p id="id_p2"></p> // <p id="id_p3"></p> $("p[id^='id']").html("以id为id开头的的p标签");
-
$("[attribute]":选择所有指定属性的元素,该属性可以是任何值。
// <p class="class_p1"></p> // <p id="id_p2"></p> // <p id="id_p3"></p> $("p[id]").html("所有id属性的p标签");
-
$("[attributeFilte[attributeFilter1]r1"):选择匹配所有指定的属性筛选器的元素。
// <p class="class_p1"></p> // <p id="id_p2"></p> // <p id="id_p3"></p> $("p[id='id_p2'][class$='p2']").html("选择id属性为'id_p2',或者class属性为p2结尾的p标签");
举例:
- $("[href]") 选取所有带有 href 属性的元素。
- $("[href='#']") 选取所有带有 href 值等于 "#" 的元素。
- $("[href!='#']") 选取所有带有 href 值不等于 "#" 的元素。
- $("[href$='.jpg']") 选取所有 href 值以 ".jpg" 结尾的元素。
3.3 jQuery CSS选择器
jQuery CSS 选择器可用于改变 HTML 元素的 CSS 属性。
下面的例子把所有 p 元素的背景颜色更改为红色:
$("p").css("background-color","red");
3.4 表单选择器(建议在其之前加上css选择器,结合以下选择器进行过滤)
- jQuery(":button")::button Selector。选择所有按钮元素和类型为按钮的元素。
- jQuery(":checkbox")::checkbox Selector。选择所有类型为复选框的元素。
- jQuery(":checked")::checked Selector。选择所有勾选的元素。
- jQuery(":disabled")::disabled Selector。选择所有被禁用的元素。
- jQuery(":enabled")::enabled Selector。选择所有可用的(注:未被禁用的元素)的元素。
- jQuery(":file")::file Selector。选择所有类型为文件(file)的元素。
- jQuery(":focus")::focus Selector。选择当前获取焦点的元素。
- jQuery(":image"): :image Selector。选择所有图像类型的元素。
- jQuery(":input")::input Selector。选择所有input, textarea, select和button元素。
- jQuery(":password")::password Selector。选择所有类型为密码的元素。
- jQuery(":radio")::radio Selector。选择所有类型为单选框的元素。
- jQuery(":submit") ::submit Selector。选择所有类型为提交的元素。
举例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- 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- 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")
-
jQuery(":hidden"):hidden selector。选择所有隐藏的元素。
补充(元素可以被认为是隐藏的几种情况):
- 它们的CSS display值时none;
- 它们是type="hidden"的表单元素;
- 它们的宽度和高度都设置为0;
- 一个祖先元素是隐藏的,因此该元素是不会在页面上显示。
-
jQuery(":visible"):visible selector。选择所有可见的元素。
如果元素占据文档中一定的空间,元素被认为是可见的。可见元素的宽度和高度,是大于零。
因此:元素的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 {
200px;
height: 200px;
background-color: red;
}
.inner {
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>
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" 的元素 |
3.7 jQuery遍历
函数 | 描述 |
---|---|
.add() | 将元素添加到匹配元素的集合中。 |
.andSelf() | 把堆栈中之前的元素集添加到当前集合中。 |
.children() | 获得匹配元素集合中每个元素的所有子元素。 |
.closest() | 从元素本身开始,逐级向上级元素匹配,并返回最先匹配的祖先元素。 |
.contents() | 获得匹配元素集合中每个元素的子元素,包括文本和注释节点。 |
.each() | 对 jQuery 对象进行迭代,为每个匹配元素执行函数。 |
.end() | 结束当前链中最近的一次筛选操作,并将匹配元素集合返回到前一次的状态。 |
.eq() | 将匹配元素集合缩减为位于指定索引的新元素。 |
.filter() | 将匹配元素集合缩减为匹配选择器或匹配函数返回值的新元素。 |
.find() | 获得当前匹配元素集合中每个元素的后代,由选择器进行筛选。 |
.first() | 将匹配元素集合缩减为集合中的第一个元素。 |
.has() | 将匹配元素集合缩减为包含特定元素的后代的集合。 |
.is() | 根据选择器检查当前匹配元素集合,如果存在至少一个匹配元素,则返回 true。 |
.last() | 将匹配元素集合缩减为集合中的最后一个元素。 |
.map() | 把当前匹配集合中的每个元素传递给函数,产生包含返回值的新 jQuery 对象。 |
.next() | 获得匹配元素集合中每个元素紧邻的同辈元素。 |
.nextAll() | 获得匹配元素集合中每个元素之后的所有同辈元素,由选择器进行筛选(可选)。 |
.nextUntil() | 获得每个元素之后所有的同辈元素,直到遇到匹配选择器的元素为止。 |
.not() | 从匹配元素集合中删除元素。 |
.offsetParent() | 获得用于定位的第一个父元素。 |
.parent() | 获得当前匹配元素集合中每个元素的父元素,由选择器筛选(可选)。 |
.parents() | 获得当前匹配元素集合中每个元素的祖先元素,由选择器筛选(可选)。 |
.parentsUntil() | 获得当前匹配元素集合中每个元素的祖先元素,直到遇到匹配选择器的元素为止。 |
.prev() | 获得匹配元素集合中每个元素紧邻的前一个同辈元素,由选择器筛选(可选)。 |
.prevAll() | 获得匹配元素集合中每个元素之前的所有同辈元素,由选择器进行筛选(可选)。 |
.prevUntil() | 获得每个元素之前所有的同辈元素,直到遇到匹配选择器的元素为止。 |
.siblings() | 获得匹配元素集合中所有元素的同辈元素,由选择器筛选(可选)。 |
.slice() | 将匹配元素集合缩减为指定范围的子集。 |
3.8 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效果
4.1 显示、隐藏和切换
1)jQuery hide()和show() 方法
语法:
$(selector).hide(speed, callback);
$(selector).show(speed, callback);
举例1(通过点击id为"butHide"或者"butShow"按钮来隐藏或者显示<p>元素):
$("#butHide").click(function() {
$("p").hide();
});
$("#butShow").click(function() {
$("p").show();
});
举例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 () {
$(".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>
举例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>-->
<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() 方法
语法:
$(selector).toggle(speed, callback);
- 可选的 speed 参数规定隐藏/显示的速度,可以取以下值:"slow"、"fast" 或毫秒。
- 可选的 callback 参数是 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 () {
$("#switch").click(function () {
$("p").toggle();
});
});
</script>
</head>
<body>
<button id="switch" type="button">切换</button>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
</body>
</html>
4.2 淡入和淡出(四种 fade 方法)
jQuery Fading 方法,通过 jQuery,可以实现元素的淡入淡出效果。
jQuery 拥有下面四种 fade 方法:
-
fadeIn():用于淡入已隐藏的元素。
$(selector).fadeIn(speed, callback);
-
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
-
可选的 callback 参数是 fading 完成后所执行的函数名称。
-
-
fadeOut():用于淡出可见元素。
$(selector).fadeOut(speed, callback);
-
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
-
可选的 callback 参数是 fading 完成后所执行的函数名称。
-
-
fadeToggle():可以在 fadeIn() 与 fadeOut() 方法之间进行切换。
$(selector).fadeToggle(speed,callback);
-
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
-
可选的 callback 参数是 fading 完成后所执行的函数名称。
如果元素已淡出,则 fadeToggle() 会向元素添加淡入效果。
如果元素已淡入,则 fadeToggle() 会向元素添加淡出效果。 -
-
fadeTo():允许渐变为给定的不透明度(值介于 0 与 1 之间)。
$(selector).fadeTo(speed, opacity, callback);
-
必需的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
-
fadeTo() 方法中必需的 opacity 参数将淡入淡出效果设置为给定的不透明度(值介于 0 与 1 之间)。
-
可选的 callback 参数是该函数完成后所执行的函数名称。
-
举例1(演示了带有不同参数的 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="80px;height:80px;display:none;background-color:red;"></div>
<!--display:none,默认该div区域不显示-->
<br>
<div id="div2" style="80px;height:80px;display:none;background-color:green;"></div>
<!--display:none,默认该div区域不显示-->
<br>
<div id="div3" style="80px;height:80px;display:none;background-color:blue;"></div>
<!--display:none,默认该div区域不显示-->
</body>
</html>
举例2(演示了带有不同参数的 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="80px;height:80px;background-color:red;"></div>
<br>
<div id="div2" style="80px;height:80px;background-color:green;"></div>
<br>
<div id="div3" style="80px;height:80px;background-color:blue;"></div>
</body>
</html>
举例3(演示了带有不同参数的 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="80px;height:80px;background-color:red;"></div>
<br>
<div id="div2" style="80px;height:80px;background-color:green;"></div>
<br>
<div id="div3" style="80px;height:80px;background-color:blue;"></div>
</body>
</html>
举例4(演示了带有不同参数的 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="80px;height:80px;background-color:red;"></div>
<br>
<div id="div2" style="80px;height:80px;background-color:green;"></div>
<br>
<div id="div3" style="80px;height:80px;background-color:blue;"></div>
</body>
</html>
4.3 滑动
jQuery 滑动方法可使元素上下滑动。
jQuery 滑动方法。通过 jQuery,您可以在元素上创建滑动效果。
jQuery 拥有以下滑动方法:
-
slideDown():用于向下滑动元素。
$(selector).slideDown(speed, callback);
-
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
-
可选的 callback 参数是滑动完成后所执行的函数名称。
-
-
slideUp():用于向下滑动元素。
$(selector).slideUp(speed, callback);
-
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
-
可选的 callback 参数是滑动完成后所执行的函数名称。
-
-
slideToggle():可以在 slideDown() 与 slideUp() 方法之间进行切换。
$(selector).slideToggle(speed, callback);
-
可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
-
可选的 callback 参数是滑动完成后所执行的函数名称。
如果元素向下滑动,则 slideToggle() 可向上滑动它们。
如果元素向上滑动,则 slideToggle() 可向下滑动它们。 -
举例1(演示了 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"); // 等价于:$(".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>
举例2(演示了 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>
举例3(演示了 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>
4.4 动画/停止动画(animate() / stop() 方法)
1)jQuery 动画 - animate() 方法
jQuery animate() 方法用于创建自定义动画。语法:
$(selector).animate({params}, speed, callback);
- 必需的 params 参数定义形成动画的 CSS 属性。
- 可选的 speed 参数规定效果的时长。它可以取以下值:"slow"、"fast" 或毫秒。
- 可选的 callback 参数是动画完成后所执行的函数名称。
举例(演示 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' });
});
});
</script>
</head>
<body>
<button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;100px;position:absolute;">
</div>
</body>
</html>
输出结果:点击按钮,div元素区域会出现从左向右的动画。
提示:默认地,所有 HTML 元素都有一个静态位置,且无法移动。
如需对位置进行操作,要记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute!
(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',
'150px'
});
});
});
</script>
</head>
<body>
<button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;100px;position:absolute;">
</div>
</body>
</html>
提示:可以用 animate() 方法来操作所有 CSS 属性吗?
是的,几乎可以!不过,需要记住一件重要的事情:当使用 animate() 时,必须使用 Camel 标记法书写所有的属性名,比如,必须使用 paddingLeft 而不是 padding-left,使用 marginRight 而不是 margin-right,等等。
同时,色彩动画并不包含在核心 jQuery 库中。
如果需要生成颜色动画,您需要从 jQuery.com 下载 Color Animations 插件。
(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',
'+=150px'
});
});
});
</script>
</head>
<body>
<button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;100px;position:absolute;">
</div>
</body>
</html>
(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;100px;position:absolute;">
</div>
</body>
</html>
(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({ '300px', opacity: '0.8' }, "slow");
div.animate({ height: '100px', opacity: '0.4' }, "slow");
div.animate({ '100px', opacity: '0.8' }, "slow");
});
});
</script>
</head>
<body>
<button>开始动画</button>
<p>默认情况下,所有 HTML 元素的位置都是静态的,并且无法移动。如需对位置进行操作,记得首先把元素的 CSS position 属性设置为 relative、fixed 或 absolute。</p>
<div style="background:#98bf21;height:100px;100px;position:absolute;">
</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 () {
$("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;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;200px;position:absolute;">HELLO</div>
</body>
</html>
【开始】按钮会启动动画。
【停止】按钮会停止当前活动的动画,但允许已排队的动画向前执行。
【停止所有】按钮停止当前活动的动画,并清空动画队列;因此元素上的所有动画都会停止。
【停止但要完成】会立即完成当前活动的动画,然后停下来。
4.5 Callback/Chaning
Callback 函数在当前动画 100% 完成之后执行。
Callback 函数在当前动画 100% 完成之后执行。
1)jQuery 动画的问题
许多 jQuery 函数涉及动画。这些函数也许会将 speed 或 duration 作为可选参数。
例子:$("p").hide("slow")
speed 或 duration 参数可以设置许多不同的值,比如 "slow", "fast", "normal" 或毫秒。
$("button").click(function(){
$("p").hide(1000);
});
由于 JavaScript 语句(指令)是逐一执行的 - 按照次序,动画之后的语句可能会产生错误或页面冲突,因为动画还没有完成。
为了避免这个情况,您可以以参数的形式添加 Callback 函数。
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 方法的完整内容,请访问以下参考手册:
- 参考:jQuery 文档操作
- 参考:jQuery 属性操作
- 参考:jQuery CSS 操作
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>
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>
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>
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>
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>
举例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>
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>
5.3 添加元素(添加新的 HTML 内容)
我们将学习用于添加新内容的四个 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>
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>
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>
<!--<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 <img> insert text</button>
<button id="btn2">After the <img> 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>
<!--<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 <img> 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;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 <div1> 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;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 <div1> 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 <p> element</button>
</body>
</html>
5.5 获取并设置CSS类(操作CSS)
jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:
- addClass():向被选元素添加一个或多个类。
- removeClass():从被选元素删除一个或多个类。
- toggleClass():对被选元素进行添加/删除类的切换操作。
- css():设置或返回样式属性。
1)jQuery addClass() 方法
举例1(展示如何向不同的元素添加 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").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() 方法设置或返回被选元素的一个或多个样式属性。
(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>This is title</h2>
<p style="background-color:#ff0000">This is a paragraph!</p>
<p style="background-color:#00ff00">This is a paragraph!</p>
<p style="background-color:#0000ff">This is a paragraph!</p>
<button>return color of element p</button>
</body>
</html>
(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>This is title</h2>
<p style="background-color:#ff0000">This is a paragraph!</p>
<p style="background-color:#00ff00">This is a paragraph!</p>
<p style="background-color:#0000ff">This is a paragraph!</p>
<p>This is a paragraph!</p>
<button>set color with element p</button>
</body>
</html>
(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)介绍几个概念
- margin和padding都是盒模型(Box Model)的重要元素,二者都是用来处理与其他盒子的距离关系进行布局的。
- 形象的介绍,夏季女生在地铁遇到色狼变态时有发生,如果选择穿上羽绒服与色狼保持距离,那就是padding内边距,如果选择移动自己的位置远离色狼,那就是margin外边距。
- 就与borde边框的位置来看,padding在border边框内,margin在border边框外。
- padding内边距会改变盒模型的大小(即宽高),margin则不会。
- margin内边距用负值,padding不可以。
<!--padding:内边距,上右下左-->
<!--margin:外边框-->
<!--border:边框-->
<!--width:element宽度-->
<!--height:element高度-->
并且规范还提供了省略的数值写法,基本如下:
- 如果margin只有一个值,表示上右下左的margin同为这个值。例如:margin:10px; 就等于 margin:10px 10px 10px 10px;
- 如果 margin 只有两个值,第一个值表示上下margin值,第二个值为左右margin的值。例如:margin:10px 20px; 就等于 margin:10px 20px 10px 20px;
- 如果margin有三个值,第一个值表示上margin值,第二个值表示左右margin的值,第三个值表示下margin的值。例如:margin:10px 20px 30px; 就等于 margin:10px 20px 30px 20px;
- 如果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(下面的例子返回指定的元素的宽度和高度,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;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;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;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;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() + "
";
txt += "Window width/height: " + $(window).width();
txt += "x" + $(window).height();
alert(txt);
});
});
</script>
</head>
<body>
<button>显示文档和窗口的尺寸</button>
</body>
</html>
举例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 () {
$("button").click(function () {
$("#div1").width(320).height(320);
});
});
</script>
</head>
<body>
<div id="div1"
style="height:100px;300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;">
</div>
<br>
<button>调整 div 的尺寸</button>
</body>
</html>
6、jQuery遍历
- 参考: 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():返回被选元素的所有祖先元素,它一路向上直到文档的根元素 ()。也可以使用可选参数来过滤对祖先元素的搜索。
- parentsUntil():返回介于两个给定元素之间的所有祖先元素。
举例1(parent() 方法,下面的例子返回每个元素的的直接父元素):
<!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="500px;">div (曾祖父)
<ul>ul (祖父)
<li>li (直接父)
<span>span</span>
</li>
</ul>
</div>
<div style="500px;">div (祖父)
<p>p (直接父)
<span>span</span>
</p>
</div>
</div>
</body>
</html>
举例2(parents() 方法,下面的例子返回所有元素的所有祖先):
<!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="500px;">div (曾祖父)
<ul>ul (祖父)
<li>li (直接父)
<span>span</span>
</li>
</ul>
</div>
</body>
</html>
举例3(parentsUntil() 方法,下面的例子返回所有 元素的所有祖先):
<!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="500px;">div (曾祖父)
<ul>ul (祖父)
<li>li (直接父)
<span>span</span>
</li>
</ul>
</div>
</body>
</html>
6.2 后代/子元素过滤/层级
后代是子、孙、曾孙等等。
通过 jQuery,您能够向下遍历 DOM 树,以查找元素的后代。
向下遍历 DOM 树。
1)方式一(遍历——后代:children(), find())
下面是两个用于向下遍历 DOM 树的 jQuery 方法:
- children():返回被选元素的所有直接子元素。该方法只会向下一级对 DOM 树进行遍历。
- find():返回被选元素的后代元素,一路向下直到最后一个后代。
举例1(children() 方法,下面的例子返回每个 元素的所有直接子元素):
<!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="500px;">div (当前元素)
<p>p (子)
<span>span (孙)</span>
</p>
<p>p (child)
<span>span (孙)</span>
</p>
</div>
</body>
</html>
举例2(children() 方法,您也可以使用可选参数来过滤对子元素的搜索。下面的例子返回类名为 "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 () {
$("div").children("p.first").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="500px;">div (当前元素)
<p class="first">p (子)
<span>span (孙)</span>
</p>
<p class="second">p (child)
<span>span (孙)</span>
</p>
</div>
</body>
</html>
举例3(find() 方法,下面的例子返回属于 后代的所有 元素):
<!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="500px;">div (当前元素)
<p class="first">p (子)
<span>span (孙)</span>
</p>
<p class="second">p (child)
<span>span (孙)</span>
</p>
</div>
</body>
</html>
举例4(find() 方法,下面的例子返回属于后代的所有后代):
<!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="500px;">div (当前元素)
<p class="1">p (子)
<span>span (孙)</span>
</p>
<p class="2">p (child)
<span>span (孙)</span>
</p>
</div>
</body>
</html>
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个子元素。 |
举例:
<!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>
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(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>
举例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() 方法,下面的例子返回 的所有同胞元素)
<!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() 方法,下面的例子返回属于 的同胞元素的所有 元素)
<!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() 方法,下面的例子返回 的下一个同胞元素)
<!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() 方法,下面的例子返回 的所有跟随的同胞元素)
<!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() 方法,下面的例子返回介于 与 元素之间的所有同胞元素)
<!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语法:$(":eq(index)"):index: 要匹配元素的索引值(从0开始计数)$(":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 {
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 {
100px;
height: 50px;
background-color: yellow;
/* float: left; */
border: 1px solid #af9898;
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() 方法,选取首个 元素内部的第一个元素,last() 方法选择最后一个 元素中的最后一个元素)
<!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>
举例6(eq() 方法,索引号从 0 开始,因此首个元素的索引号是 0 而不是 1。下面的例子选取第二个 元素(索引号 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"*) 的所有 元素)
<!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" 的所有 元素)
<!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 事件 |
8、JavaScript异步编程的四种方法
- 参考:http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFjavascript.html
- 参考:Asynchronous JS: Callbacks, Listeners, Control Flow Libs and Promises
8.1 Promises对象(jQuery Deferred对象的使用)
- 参考:http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html
- 参考:http://api.jquery.com/category/deferred-object/
// 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