一,jQuery的配置
这里以compressed为例,根据喜好也可以选择uncompressed版本。
进入jQuery代码中,右键另存为,保存到自己项目中:
导入jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../static/js/jquery-3.7.1.min.js"></script>
二,jQuery选择器
在jQuery中$就代表jQuery,它可以选择匹配的元素并返回一个jQuery对象。
(1)类选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../static/js/jquery-3.7.1.min.js"></script>
<style>
.container {
height: 200px;
}
</style>
<body>
<div class="container"></div>
<script>
let div = document.querySelector(".container");
div.innerHTML = "Hello jQuery";
// --------------------以下与上面代码一致-----------------------
$(".container").html("Hello jQuery");
</script>
</body>
</html>
(2)元素选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../static/js/jquery-3.7.1.min.js"></script>
<style>
.container {
height: 200px;
}
</style>
<body>
<div class="container"></div>
<div id="root"></div>
<span></span>
<script>
$("span").html("span");
</script>
</body>
</html>
(3)ID选择器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../static/js/jquery-3.7.1.min.js"></script>
<style>
.container {
height: 200px;
}
</style>
<body>
<div class="container"></div>
<div id="root"></div>
<span></span>
<script>
$("#root").html("haha");
</script>
</body>
</html>
(4)子元素选择器("parent > child")
$(".container>li").addClass("list");
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../static/js/jquery-3.7.1.min.js"></script>
<style>
.test {
border: 3px solid green;
}
</style>
<body>
<ul class="topnav">
<li>Item1</li>
<li>
<ul>
<li>child Item1</li>
<li>child Item2</li>
<li>child Item3</li>
</ul>
</li>
<li>Item3</li>
</ul>
<script>
$(".topnav>li").addClass("test");
</script>
</body>
</html>
对于父级元素和子级元素,都可以用类选择器,元素选择器,ID选择器来替代。
(5)后代元素选择器("parent child")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="../static/js/jquery-3.7.1.min.js"></script>
<style>
.test {
border: 3px solid green;
}
</style>
<body>
<ul class="topnav">
<li>Item1</li>
<li>
<ul>
<li>child Item1</li>
<li>child Item2</li>
<li>child Item3</li>
</ul>
</li>
<li>Item3</li>
</ul>
<script>
$(".topnav li").addClass("test");
</script>
</body>
</html>
区别就在于下面框选的三个li元素是否被选择,子代只会在父级元素的下一级找,后代元素会在父级元素的所有后代中寻找。