介绍jQuery的基本选择器,包括元素选择器、ID选择器、类选择器、通配符选择器和组合选择器的用法。
基本选择器是 jQuery 中最常用的选择器,包括元素选择器、ID 选择器、类选择器、通配符选择器和组合选择器。
$("p") // 选择所有 p 元素
$("div") // 选择所有 div 元素
$("a") // 选择所有 a 元素
$("#test") // 选择 id="test" 的元素
$("#header") // 选择 id="header" 的元素
$(".test") // 选择所有 class="test" 的元素
$(".active") // 选择所有 class="active" 的元素
$("*") // 选择所有元素
$("p, .test") // 选择所有 p 元素和 class="test" 的元素
$("div, p, span") // 选择所有 div、p、span 元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>基本选择器示例</title>
<style>
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}
.demo-section {
margin-bottom: 30px;
padding: 20px;
background-color: #f8f9fa;
border-radius: 8px;
}
.box {
width: 100px;
height: 100px;
background-color: #3498db;
color: white;
text-align: center;
line-height: 100px;
border-radius: 8px;
margin: 10px;
display: inline-block;
}
.test {
background-color: #e74c3c;
}
button {
padding: 10px 20px;
margin: 5px;
background-color: #3498db;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #2980b9;
}
.info-box {
padding: 15px;
margin-top: 15px;
background-color: white;
border-radius: 5px;
border: 2px solid #3498db;
}
</style>
</head>
<body>
<div class="container">
<h1>jQuery 基本选择器</h1>
<div class="demo-section">
<h3>选择器测试</h3>
<div class="box" id="box1">盒子 1</div>
<div class="box test" id="box2">盒子 2</div>
<div class="box" id="box3">盒子 3</div>
<p class="test">段落 1</p>
<p>段落 2</p>
<button onclick="testElement()">元素选择器</button>
<button onclick="testId()">ID 选择器</button>
<button onclick="testClass()">类选择器</button>
<button onclick="testMultiple()">多元素选择器</button>
<button onclick="resetAll()">重置</button>
<div id="result" class="info-box"></div>
</div>
</div>
<script>
function showMessage(msg) {
$("#result").text(msg);
}
function testElement() {
var count = $(".box").length;
showMessage("元素选择器 $('.box'):选择了 " + count + " 个元素");
$(".box").css("background-color", "#f39c12");
}
function testId() {
var text = $("#box2").text();
showMessage("ID 选择器 $('#box2'):" + text);
$("#box2").css("background-color", "#9b59b6");
}
function testClass() {
var count = $(".test").length;
showMessage("类选择器 $('.test'):选择了 " + count + " 个元素");
$(".test").css("background-color", "#1abc9c");
}
function testMultiple() {
var count = $(".box, .test").length;
showMessage("多元素选择器 $('.box, .test'):选择了 " + count + " 个元素");
$(".box, .test").css("background-color", "#34495e");
}
function resetAll() {
$(".box").css("background-color", "#3498db");
$(".test").css("background-color", "#e74c3c");
$("#result").empty();
}
</script>
</body>
</html>
基本选择器是 jQuery 中最简单也是最常用的选择器,掌握这些选择器是学习 jQuery 的基础。