JQuery 中 :first 選擇器的使用注意點
阿新 • • 發佈:2018-12-25
<!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"分開寫,其他類似的選擇器也要注意哦!