1.jQuery描述
jQuery 库可以通过一行简单的标记被添加到网页中。
jQuery 库 - 特性
jQuery 是一个 JavaScript 函数库。
jQuery 库包含以下特性:
-
HTML 元素选取
-
HTML 元素操作
-
CSS 操作
-
HTML 事件函数
-
JavaScript 特效和动画
-
HTML DOM 遍历和修改
-
AJAX
-
Utilities
2.添加 jQuery 库
jQuery 库位于一个 JavaScript 文件中,其中包含了所有的 jQuery 函数。
2.1.下载jQuery 库
共有两个版本的 jQuery 可供下载:一份是精简过的,另一份是未压缩的(供调试或阅读)。
链接:http://jquery.com/download/#Download_jQuery
2.2.位置
下载的jQuery文件存放位置如下
2.3.添加 代码
<head>
<script src="js/jquery-3.3.1.min.js"></script>
</head>
2.4.库的替代
Google 和 Microsoft 对 jQuery 的支持都很好。
如果您不愿意在自己的计算机上存放 jQuery 库,那么可以从 Google 或 Microsoft 加载 CDN jQuery 核心文件。
2.4.1.使用 Google 的 CDN
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs
/jquery/1.4.0/jquery.min.js"></script>
</head>
2.4.2.使用 Microsoft 的 CDN
<head>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery
/jquery-1.4.min.js"></script>
</head>
2.5.简单举例
代码
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p").hide();
});
});
</script>
</head>
<body>
<h2>这是标题</h2>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>点击这里</button>
</body>
</html>
效果
3.jQuery 语法
通过 jQuery,您可以选取(查询,query) HTML 元素,并对它们执行“操作”(actions)。
jQuery 语法是为 HTML 元素的选取编制的,可以对元素执行某些操作。
基础语法是:$(selector).action()
- 美元符号定义 jQuery
- 选择符(selector)“查询”和“查找” HTML 元素
- jQuery 的 action() 执行对元素的操作
3.1.$(this).hide()
演示 jQuery hide() 函数,隐藏当前的 HTML 元素。
代码
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$(this).hide();
});
});
</script>
</head>
<body>
<button type="button">Click me</button>
</body>
</html>
效果
3.2.$("#test").hide()
演示 jQuery hide() 函数,隐藏 id="test" 的元素。
代码
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
效果
3.3.$("p").hide()
演示 jQuery hide() 函数,隐藏所有 <p> 元素。
代码
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(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>
效果
3.4.$(".test").hide()
演示 jQuery hide() 函数,隐藏所有 class="test" 的元素。
代码
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>
<h2 class="test">This is a heading</h2>
<p class="test">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">Click me</button>
</body>
</html>
效果