Basic Selector Learning in jQuery (Supplementary)

First look at the overall code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>05jQuery Basic selector learning in C</title>
		<script type="text/javascript" src="js/jquery-1.9.1.js" charset="UTF-8"></script>
		<style>
			div{
				width: 300px;
				height: 300px;
				border: 2px solid darkred;
			}
		
		</style>
		
		<script>
		$(function(){
			$("ul li:first").css("color","aqua");Only the first row discolors
			$("ul li").first().css("color","aqua");Only the first row discolors
			
			$("ul li:last").css("color","aqua");Only the last line is discolored
			$("ul li").first().css("color","aqua");Only the last line is discolored
			
			$("ul li:odd").css("color","aqua");//Only odd lines change color, starting with subscript 0
			$("ul li:even").css("color","royalblue");//Only even rows change color, starting with subscript 0
	
			$("ul li:eq(3)").css("color","aqua");Starting from 0 with index subscripts, the third element changes color
			
			/*************Subselector****************************************/
			$("ul li:first-child").css("color","aqua");Colour the first element of all lists
			$("ul li:last-child").css("color","aqua");Colour the last element of all lists
			$("ul li:only-child").css("color","aqua");There will be only one element change
			$("ul li:nth-child(2)").css("color","aqua");Colour the second element of all lists
		})
			
		</script>
	</head>
	<body>
		<div>
			<ul>
				<li>Listing 1</li>
				<li>Listing 2</li>
				<li>Listing 3</li>
				<li>Listing 4</li>
			</ul>
			<ul>
				<li>Listing 1</li>
				<li>Listing 2</li>
				
			</ul>
			<ul>
				<li>Listing 1</li>
			</ul>
		</div>
	</body>
</html>

We analyze jQuery operations line by line:

1. See all the elements in ul as a whole and operate them as a whole (these are two ways of jQuery):

$("ul li:first").css("color","aqua");
$("ul li").first().css("color","aqua");

So only the first line will change color:

 

2. Similar to the first one, the last one will be discolored:

$("ul li:last").css("color","aqua");
$("ul li").first().css("color","aqua");

 

3. Even and odd row discoloration can be considered as interlace discoloration (index subscript 0 begins):

$("ul li:odd").css("color","aqua");
$("ul li:even").css("color","royalblue");

4. Change the color of the element by index:

$("ul li:eq(3)").css("color","aqua");

Thus, this method begins with index subscript 0.

 

All of these take ul as a whole, and our sub-selectors will be separated from li.

$("ul li:first-child").css("color","aqua");

 

$("ul li:last-child").css("color","aqua");

 

 

$("ul li:only-child").css("color","aqua");

$("ul li:nth-child(2)").css("color","aqua");

 

 

 

 

 

 

 

 

 

 

Tags: JQuery Javascript

Posted on Tue, 08 Oct 2019 15:08:50 -0700 by Randuin