類選擇器是 jQuery 中非常基礎卻又常用的選擇器。通過不同的組合方式,可以精準地選取頁面元素。下面通過一個示例來說明幾種常見的類選擇器用法。
先看一段 HTML 結構,其中包含了 first_div、second_div、first_span、eric_sun_class 等若干 class:
<div class="first_div">This is the first div</div> <div class="second_div">This is the second div</div> <div class="first_div"> <span class="first_span">This is the first span</span> </div> <span class="first_span eric_sun_class">This is the first span + eric sun class.</span> <span class="eric_sun_class">This is the eric sun class.</span>
接下來看幾種選擇器的差異:
理解「逗號=或、空格=後代、緊挨着=與」這三種關係,是熟練使用 jQuery 選擇器的基礎。掌握它們,就能在頁面中靈活、精準地定位到你想要的元素。