1. 程式人生 > >Jquery選擇器練習(二)

Jquery選擇器練習(二)

Jquery的選擇器非常強大,只要運用熟悉,方可對Dom操作得心應手。一些選擇器和CSS偽類很相似,很容易引起混淆,需要多加練習和注意。

<!DOCTYPE html>
<html lang="zh-cn">
	<head>
		<title>Test</title>
		<meta charset="UTF-8" />
		<script src="js/jquery-1.11.1.min.js"></script>
		<script src="js/index.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				initElementBgColor();
			});
			var initElementBgColor = function() {
				$("div.smallBox:odd").css("background", "#ccc");
				$("div.smallBox:even").css("background", "#ccc");
				$(".smallBox:first").css("background", "#ccc");
				$(".smallBox:last").css("background", "#ccc");
				$(".smallBox:nth-child(2)").css("background", "#ccc");
				$(".smallBox:nth-child(n+1)").css("background", "#ccc");
				$(".smallBox:nth-child(2n)").css("background", "#ccc");
				$(".smallBox:nth-child(2n+1)").css("background", "#ccc");
				$(".smallBox:nth-child(-3n+100)").css("background", "#ccc");
				$(".smallBox:gt(3)").css("background", "#ccc");
				$(".smallBox:lt(3)").css("background", "#ccc");
				$(".smallBox:eq(5)").css("background", "#ccc");
				$(".smallBox:not(:empty)").css("background", "#ccc");
				$(".smallBox:hidden").css("display", "block");
				$(".smallBox:not(:visible)").css("display", "block");
				$(".box .smallBox,:visible").css("display", "block");
				$(".box .smallBox p:contains(4)").css("background", "#ccc");
				$(".box :header").css("background", "#ccc");
			}
		</script>

		<style type="text/css" >
			* {margin: 0;padding: 0;}
			.box {border: 1px solid;}
			.smallBox {
				width: 100px;
				height: 100px;
				border: 1px solid red;
				margin-left: 91px;
				float: left;
				font-size: 80px;
				line-height: 100px;
				text-align: center;
			}
			.clear {
				clear: both;
				height: 0px;
				overflow: hidden;
			}
			.show {display: none;}
			.able {visibility: hidden;}
		</style>
	</head>
	<body>
		<div class="box">
			<div class="smallBox">1</div>
			<div class="smallBox">2</div>
			<div class="smallBox">3</div>
			<div class="smallBox">
				<p>4</p>
			</div>
			<div class="smallBox">5</div>
			<div class="smallBox">6</div>
			<div class="smallBox">7</div>
			<div class="smallBox show">8</div>
			<div class="smallBox able">9</div>
			<div class="clear"></div>
			<div>
				<h1>H1H1H1H1H1H1H1H1H1H1H1H1H1H1H1</h1>
				<h2>H2H2H2H2H2H2H2H2H2H2H2H2H2H2H2</h2>
			</div>
		</div>
	</body>
</html>