選擇器允許您對元素組或單個元素進(jìn)行操作。
————————————————————
jQuery 選擇器
在前面的章節(jié)中,我們展示了一些有關(guān)如何選取 HTML 元素的實例。
關(guān)鍵點是學(xué)習(xí) jQuery 選擇器是如何準(zhǔn)確地選取您希望應(yīng)用效果的元素。
jQuery 元素選擇器和屬性選擇器允許您通過標(biāo)簽名、屬性名或內(nèi)容對 HTML 元素進(jìn)行選擇。
選擇器允許您對 HTML 元素組或單個元素進(jìn)行操作。
在 HTML DOM 術(shù)語中:
選擇器允許您對 DOM 元素組或單個 DOM 節(jié)點進(jìn)行操作。
————————————————————
jQuery 元素選擇器
jQuery 使用 CSS 選擇器來選取 HTML 元素。
- $("p") 選取 <p> 元素。
- $("p.intro") 選取所有 class="intro" 的 <p> 元素。
- $("p#demo") 選取 id="demo" 的第一個 <p> 元素。
————————————————————
jQuery 屬性選擇器
jQuery 使用 XPath 表達(dá)式來選擇帶有給定屬性的元素。
- $("[href]") 選取所有帶有 href 屬性的元素。
- $("[href='#']") 選取所有帶有 href 值等于 "#" 的元素。
- $("[href!='#']") 選取所有帶有 href 值不等于 "#" 的元素。
- $("[href$='.jpg']") 選取所有 href 值以 ".jpg" 結(jié)尾的元素。
————————————————————
jQuery CSS 選擇器
jQuery CSS 選擇器可用于改變 HTML 元素的 CSS 屬性。
下面的例子把所有 p 元素的背景顏色更改為紅色:
- <html>
- <head>
- <script type="text/javascript" src="/jquery/jquery.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $("button").click(function(){
- $("p").css("background-color","yellow");
- });
- });
- </script>
- </head>
-
- <body>
- <h2>This is a heading</h2>
- <p>This is a paragraph.</p>
- <p>This is another paragraph.</p>
- <button type="button">Click me</button>
- </body>
-
- </html>
<html><head><script type="text/javascript" src="/jquery/jquery.js"></script><script type="text/javascript">$(document).ready(function(){$("button").click(function(){$("p").css("background-color","yellow");});});</script></head><body><h2>This is a heading</h2><p>This is a paragraph.</p><p>This is another paragraph.</p><button type="button">Click me</button></body></html>
————————————————————
語法 描述
- $(this) 當(dāng)前 HTML 元素
- $("p") 所有 <p> 元素
- $("p.intro") 所有 class="intro" 的 <p> 元素
- $(".intro") 所有 class="intro" 的元素
- $("#intro") id="intro" 的第一個元素
- $("ul li:first") 每個 <ul> 的第一個 <li> 元素
- $("[href$='.jpg']") 所有帶有以 ".jpg" 結(jié)尾的 href 屬性的屬性
- $("div#intro .head") id="intro" 的 <div> 元素中的所有 class="head" 的元素