1. 程式人生 > >JQuery 中 :first 選擇器的使用注意點

JQuery 中 :first 選擇器的使用注意點

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 	
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
	$(function(){
		$("#ee").bind("click", function(){
			$("div:first").attr("id", "test");
			$("#test").append("<button>fffffffffffffffff</button>");
		});
	});
</script>
</head>
<body>
	<button id="ee" >eeeeeeeeee</button>
	<div style="background: red;">
		<button >ddddddddd</button>
		<button >hhhhhhhhh</button>
	</div>
</body>
</html>

如果將上面程式碼中的

$("div:first").attr("id", "test");

更換為

$("div   :first").attr("id", "test");

就會發現執行的結果是不一樣的,如下面兩圖:

第一種



 
 
 第二種




 
 所以,記得不要把"div:first"分開寫,其他類似的選擇器也要注意哦!

  • 78905f5e-e174-31c9-b1c3-e409fef7bff9-thumb.png
  • 大小: 2.8 KB
  • 181822a3-076a-385f-89ff-6d3ce6757a91-thumb.png
  • 大小: 2.3 KB