1. 程式人生 > >【前端】jQuery選擇器

【前端】jQuery選擇器

<!DOCTYPE html>
<html>
<head>
	<title>jQuery | Selectors</title>
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
	<style>
		body {
			font-size: 17px;
			font-family: arial;
			background: #f4f4f4;
			line-height: 1..5em;
		}

		header {
background: #333; color: #fff; padding: 20px; text-align: center; border-bottom: 4px #000 solid; margin-bottom: 10px; } #container { width:90%; margin: auto; padding: 10px; }
</style> </head> <body> <header> <h1>jQuery</h1> </header
>
<div id="container"> <h1 id="heading1"> Heading One</h1> <p id="para1">Hello</p> <h1 class="heading2">Heading Two</h1> <p class="para2">World<span> TEST </span></p> <ul id="list"> <li>List Item </li> <
li
>
List Item </li> <li>List Item </li> <li>List Item </li> <li>List Item </li> <li>List Item </li> </ul> <input type="button" value="Button 1"> <input type="submit" value="Button 2"> <input type="text"> <a href="https://google.com">Google</a> <a href="https://yahoo.com">Yahoo</a> </div> <script> // $('h1').hide() // 標籤名選擇 // $('h1#heading1').hide(); // 標籤名 + id組合選擇 // $('h1.heading2').hide() // 標籤名 + 類選擇 // $('p span').css('color', 'red') // p下面的span,修改顏色 $('ul#list li:first').css('color', 'red') $('ul#list li:last').css('color', 'green') $('ul#list li:even').css('background-color', 'yellow') $('ul#list li:odd').css('background-color', '#ccc') $('ul#list li:nth-child(3n)').css('list-style', 'none') // 按照型別選擇 $(':button').hide() $(':submit').hide() $(':text').hide() // 選擇連結 $('[href]').css('color', 'red') $('a[href="https://yahoo.com"]').css('color', 'green') // 全選 // $('*').hide() </script> </body> </html>

顯示效果如下:

在這裡插入圖片描述

程式碼可以直接閱讀,註釋比較明確。總體看,jQuery選擇器用起來非常簡潔,且提供了直接操作元素的方法。

END.