萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 選擇器完整指南:從基礎到進階的 30+ 選擇器用法

基本選擇器

選擇器說明示例
#idID 選擇器$('#main')
element標籤選擇器('div')
.class類選擇器('.active')
*通配符('*')
selector1, selector2群組選擇器('div, span, .cls')

層次選擇器

選擇器關係示例
ancestor descendant後代(任意層級)('#nav li')
parent > child直接子元素('ul > li')
prev + next緊鄰的下一個同輩('.active + li')
prev ~ siblings之後所有同輩('.active ~ li')

基礎過濾選擇器


// 位置
$('li:first')        // 第一個
$('li:last')         // 最後一個
$('li:eq(2)')        // 索引 2(第 3 個)
$('li:gt(2)')        // 索引 > 2
$('li:lt(2)')        // 索引 < 2
$('li:even')         // 偶數索引(0,2,4...)
$('li:odd')          // 奇數索引(1,3,5...)

// 否定
$('li:not(.active)') // 不含 .active 類

// 表單
$('input:focus')     // 當前聚焦
$('input:checked')   // 勾選的 checkbox/radio
$('option:selected') // 選中的 option
$('input:disabled')  // 禁用的
$('input:enabled')   // 啟用的

內容過濾選擇器


$('div:contains("文字")')     // 包含指定文本
$('div:empty')                // 無子節點(含文本節點)
$('div:has(p)')               // 包含 p 元素
$('div:parent')               // 有子節點

屬性選擇器


$('[href]')                    // 有 href 屬性
$('[href="link.html"]')        // 屬性精確匹配
$('[href!="link.html"]')       // 屬性不等於
$('[href^="https"]')           // 以 https 開頭
$('[href$=".pdf"]')            // 以 .pdf 結尾
$('[href*="github"]')          // 包含 github
$('[class~="active"]')         // 類名包含 active (空格分隔)
$('[class|="btn"]')            // 類名以 btn- 開頭
$('[id][name="test"]')         // 多屬性 AND

子元素過濾選擇器


$('ul li:nth-child(2)')       // 第 2 個子元素
$('ul li:nth-child(2n)')      // 偶數子元素
$('ul li:nth-child(2n+1)')    // 奇數子元素
$('ul li:first-child')        // 第一個子元素
$('ul li:last-child')         // 最後一個子元素
$('ul li:only-child')         // 唯一子元素
$('ul li:nth-last-child(2)')  // 倒數第 2 個

表單專用選擇器


(':input')      // 所有 input, textarea, select, button
(':text')       // type=text
(':password')   // type=password
(':radio')      // type=radio
(':checkbox')   // type=checkbox
(':submit')     // type=submit
(':image')      // type=image
(':reset')      // type=reset
(':button')     // type=button 或 button 元素
(':file')       // type=file
(':hidden')     // type=hidden 或隱藏元素

jQuery 對象遍歷方法


const $items = $('.item');

// each 遍歷
$items.each(function(index, element) {
    // this === element (DOM)
    // $(this) === jQuery 對象
    console.log(index, this.id);
});

// map 轉換
const ids = $items.map(function() { return this.id; }).get(); // 純數組

// filter 過濾
const $visible = $items.filter(':visible');

// find 後代查找
$items.find('.child');

// closest 祖先查找
$(this).closest('.container');

// siblings 同輩
$(this).siblings('.active');

// next/prev 相鄰
$(this).next(); $(this).prev();

// parent/parents 父級
$(this).parent(); $(this).parents('.wrapper');

性能優化建議

  1. ID 選擇器最快:$('#id') 直接調用 getElementById
  2. 避免通配符:$('*') 遍歷所有元素
  3. 指定上下文:$('.class', context) 限制搜索範圍
  4. 緩存選擇結果:const $el = $('#id'); $el.doSomething();
  5. 鏈式調用:$el.addClass('a').removeClass('b').fadeIn();
  6. 事件委託:$('#parent').on('click', '.child', fn);

原生 JS 替代方案


// 現代瀏覽器原生 API 完全覆蓋 jQuery 選擇器功能
document.querySelector('#id');           // $('#id')
document.querySelectorAll('.class');     // $('.class')
document.querySelectorAll('div > p');    // $('div > p')
element.closest('.parent');              // $(el).closest('.parent')
element.matches('.active');              // $(el).is('.active')
element.classList.toggle('active');      // $(el).toggleClass('active')

// 遍歷
element.querySelectorAll('.item').forEach(el => { ... });
[...element.querySelectorAll('.item')].map(el => el.id);
copyright © 萬盛學電腦網 all rights reserved