jQuery是一个开源的JavaScript库,由John Resig于2006年创建。它使HTML文档遍历和操作、事件处理、动画和Ajax更加简单,并且可以在多种浏览器中工作。
有两种主要方式引入jQuery:
<!-- 使用Google CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!-- 使用jQuery官方CDN -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="/path/to/jquery-3.7.1.min.js"></script>
下面是一个简单的jQuery示例,当点击按钮时隐藏一个段落:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p id="demo">点击按钮我会消失!</p>
<button id="hideBtn">隐藏段落</button>
<script>
$(document).ready(function(){
$("#hideBtn").click(function(){
$("#demo").hide();
});
});
</script>
</body>
</html>
jQuery的基本语法是:$(selector).action()
$ 符号定义jQuery(selector) 查询HTML元素.action() 执行对元素的操作$(this).hide() // 隐藏当前元素
$("p").hide() // 隐藏所有<p>元素
$(".test").hide() // 隐藏所有class="test"的元素
$("#test").hide() // 隐藏id="test"的元素
为了防止文档在完全加载之前运行jQuery代码,所有jQuery代码都应该包含在文档就绪事件中:
$(document).ready(function(){
// jQuery代码写在这里
});
// 简写形式
$(function(){
// jQuery代码写在这里
});
jQuery选择器允许您选择和操作HTML元素。它们基于CSS选择器,并添加了一些自定义选择器。
| 选择器 | 示例 | 描述 |
|---|---|---|
| 元素选择器 | $("p") |
选择所有<p>元素 |
| ID选择器 | $("#test") |
选择id="test"的元素 |
| 类选择器 | $(".test") |
选择所有class="test"的元素 |
| 所有元素 | $("*") |
选择所有元素 |
| 当前元素 | $(this) |
选择当前HTML元素 |
下面是一个包含多种操作的jQuery示例:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #3498db;
margin: 10px;
display: inline-block;
}
</style>
</head>
<body>
<button id="btn1">隐藏所有段落</button>
<button id="btn2">显示所有段落</button>
<button id="btn3">切换显示</button>
<button id="btn4">添加新段落</button>
<div id="content">
<p>段落1</p>
<p class="special">特殊段落</p>
<p>段落2</p>
</div>
<div class="box"></div>
<script>
$(document).ready(function(){
// 隐藏所有段落
$("#btn1").click(function(){
$("p").hide(1000);
});
// 显示所有段落
$("#btn2").click(function(){
$("p").show(1000);
});
// 切换显示/隐藏
$("#btn3").click(function(){
$(".special").toggle(500);
});
// 添加新段落
$("#btn4").click(function(){
$("#content").append("<p>新添加的段落</p>");
});
// 盒子点击事件
$(".box").click(function(){
$(this).css("background-color", "#e74c3c");
});
});
</script>
</body>
</html>