jQuery基础选择器和层次选择器示例

一、基础选择器


<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Documenttitle>
	<script type="text/javascript" src="jquery-3.3.1.js">script>
	<script>
		$(function(){
			//ID选择器
			$("#btn1").click(function(){
				$("#par").css("background","pink");
			});

			//类选择器
			$("#btn2").click(function(){
				$(".par").css("background","lightblue");
			});

			//并集选择器
			$("#btn3").click(function(){
				$("#test1,#test2,.test").css("background","lightgreen");
			});

			//交集选择器
			$("#btn4").click(function(){
				$("p#part").css("background","purple");
			});

			//全局选择器 
			$("#btn5").click(function(){
				$("*").css("background","lightpink");
			});
		})

	script>
head>
<body>
	<input type="button" value="标签选择器" id="btn1">
	<input type="button" value="类选择器" id="btn2">
	<input type="button" value="并集选择器" id="btn3">
	<input type="button" value="交集选择器" id="btn4">
	<input type="button" value="全局选择器" id="btn5">

	<p id="par">第1行p>
	<p class="par">第2行p>
	<p>第3行p>
	<p class="par">第4行p>
	<p id="part">第5行p>
	<p id="test1">第6行p>
	<p id="test2">第7行p>
	<p class="test">第8行p>
	<p class="test">第9行p>
	<p class="test">第10行p>
body>
html>

二、层次选择器

 
 <html lang="en">
 <head>
 	<meta charset="UTF-8">
 	<title>Documenttitle>
 	<script type="text/javascript" src="jquery-3.3.1.js">script>
 	<script>
 		$(function(){
 			//后代选择器
 			$("#btn1").click(function(){
 				$("#mydiv1 p").css("background","lightgreen");
 			});

 			//子选择器
 			$("#btn2").click(function(){
 				$("#mydiv2 > span").css("background","lightblue");
 			});

 			//相邻选择器
 			$("#btn3").click(function(){
 				$("#mydiv2 + div").css("background","lightpink");
 			});

 			//不相邻的情况下使用相邻选择器
 			$("#btn4").click(function(){
 				$("#mydiv3 + div").css("background","red");
 			});

 			//兄弟选择器
 			$("#btn5").click(function(){
 				$("#mydiv4 ~ div").css("background","purple");
 			})
 		})
 	script>
 head>
 <body>
 	<input type="button" value="后代选择器" id="btn1">
 	<input type="button" value="子选择器" id="btn2">
 	<input type="button" value="相邻选择器" id="btn3">
 	<input type="button" value="相邻选择器两个同类元素必须相邻" id="btn4">
 	<input type="button" value="选择器" id="btn5">

 	<div id="mydiv1">
 		<p>
 			<span>spanspan>
 			<p>Take is easy,show me the codep>
 		p>
 		<p>Codingp>
 		<p>
 			<span>javascriptspan>
 		p>
 	div>
 	<hr>
 	<div id="mydiv2">
 		<div>
 			<p>Nodep>
 			<span>webkitspan>
 		div>
 		<span>jQueryspan>
 	div>
 	<div id="mydiv3">Coding is fun.div>
 	<hr>
 	<div id="mydiv4">Show me the code.div>
 	<hr>
 	<div id="mydiv5">
 		<p>font-sizep>
 		<div>
 			<div>
 				<p>Lessp>
 			div>
 		div>
 	div>
 	<hr>
 	<div id="mydiv6">
 		<span>spanspan>
 		<div>
 			<p>Angularp>
 		div>
 	div>
 body>
 html>

你可能感兴趣的:(前端)