在jQ中使用$()语法访问元素 ,访问document元素$(document)。
访问ready()函数:$(document).ready().
使用$(document).ready()
1 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script> 2 </head> 3 4 <body> 5 <script type="text/javascript"> 6 $(document).ready(function() { 7 alert('hi'); 8 }); 9 </script>
1使用选择器
1.1 根据Id选择元素
<a href="#" id="linkOne">Link</a> 对于js 访问是: getElementById("linkOne") 对于jQ访问时: $("#linkOne")
1.2 类选择器
<div class="spacialClass">
jQ访问:$(".spacialClass")
1.3根据层级选择元素
1 <div id="leftNav"> 2 <a href="link1.html">link 1</a> 3 <a href="link2.html">link 2</a> 4 </div>
如果想要得到特定<div>元素内的所有锚
jQ中获取两个锚元素的语法:$("#leftNav a")
更一般地,如果想要元素的直接后代,使用大于号:$("div>p"),该语法生成的是<div>元素直接后代的<p>元素但不包括选定<p>元素内的任意<p>元素。
可以使用:nth-child()选择器选择一组中的第n个孩子。
如选择每个<p>元素的第三个孩子:$("P:nth-child(3)")
1.4根据位置选择元素
<p>First p</p> <p>Second p</p> <p>Third p</p>
jQ选族器很贪婪。$('p')语法选择所有的锚标签。
在页面内选择第一个<p>元素:$("P:first").
选择最后一个<p>元素:$("p:last"),要选择第二个元素:$("p")[1]还可以这样编写$("p:eq(1)")
每隔一个元素选择一个:$("p:even")或者$("p:odd")
1 <body> 2 <table> 3 <tr> 4 <td>Row 1 Column 1 of the table</td> 5 <td>Row 1 Column 2 of the table</td> 6 </tr> 7 <tr> 8 <td>Row 2 Column 1 of the table</td> 9 <td>Row 2 Column 2 of the table</td> 10 </tr> 11 <tr> 12 <td>Row 3 Column 1 of the table</td> 13 <td>Row 3 Column 2 of the table</td> 14 </tr> 15 <tr> 16 <td>Row 4 Column 1 of the table</td> 17 <td>Row 4 Column 2 of the table</td> 18 </tr> 19 <tr> 20 <td>Row 5 Column 1 of the table</td> 21 <td>Row 5 Column 2 of the table</td> 22 </tr> 23 </table> 24 <script type="text/javascript"> 25 /*使用$(document).ready()函数和odd选择器将背景颜色设置为十六进制*/ 26 $(document).ready(function( ) { 27 $('tr:odd').css("background","#abacab"); 28 }); 29 </script> 30 </body>
显示结果如下