萬盛學電腦網

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

jQuery 排除當前元素的選擇器技巧

場景

點擊某個連結,其他連結變紅,當前保持原色。

核心代碼

var $links = $('a');
$links.click(function() {
    $links.not(this).css('color', 'red'); // 排除 this
    $(this).css('color', ''); // 重置當前
});

.not() 多種用法

// 1. DOM 元素
$links.not(this)

// 2. 選擇器字串
$('li').not('.active')

// 3. jQuery 對象
var $active = $('li.active');
$('li').not($active)

// 4. 函數過濾
$('li').not(function(i, el) { return $(el).data('skip'); })

相關方法

  • .filter(selector):保留匹配元素
  • .siblings(selector):獲取同胞元素(常用於導航高亮)
  • .eq(index) / .first() / .last():按索引取單個

導航高亮最佳寫法

$('#nav a').click(function() {
    $(this).addClass('active').siblings().removeClass('active');
});
copyright © 萬盛學電腦網 all rights reserved