[jQuery]選取器--子系物件的選取

[jQuery]選取器--子系物件的選取

語法:

  • 子系物件第幾個
    • :nth-child(index)
    • index從1開始
  • 第一個子系條件的物件
    • :first-child
  • 最後一個子系條件的物件
    • :last-child
  • 只有一個子系條件的物件
    • :only-child

 

範例:

<HTML>
	<HEAD>
		<Script Type="text/javascript" src="js/jQuery.js"></Script>
		<Script Type="text/javascript">
			$(document).ready(function(){
				$('#btn1').click(function(){
					$('ul li:nth-child(2)').addClass('st1');
					$('ul li:not(:nth-child(2))').addClass('st2');
				});
				$('#btn2').click(function(){
					$('ul li:first-child').addClass('st1');
				});
				$('#btn3').click(function(){
					$('ul li:last-child').addClass('st2');
				});
				$('#btn4').click(function(){
					$('ul li:only-child').addClass('st3');
				});
			})
		</Script>
		<style type="text/css">
			.st1
			{
				background-Color:pink;
			}
			.st2
			{
				background-Color:Yellow;
			}
			.st3
			{
				background-Color:green;
			}
		</style>
	</HEAD>
	<BODY>
		<input type="Button" id="btn1" name="btn1" value="nth-child"><br />
		<input type="Button" id="btn2" name="btn2" value="first-child"><br />
		<input type="Button" id="btn3" name="btn3" value="last-child"><br />
		<input type="Button" id="btn4" name="btn4" value="only-child"><br />
		<hr />
		<ul>
			<li>Yahoo</li>
			<li>Google</li>
			<li>YouTube</li>
		</ul>
		<ul>
			<li>Link1</li>
			<li>Link2</li>
			<li>Link3</li>
		</ul>
		<ul>
			<li>Link1</li>
		</ul>
	</BODY>
</HTML>

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat