2012-02-27 173 views
1

我正在尋找一個函數來將類應用於除點擊之外的所有鏈接。jquery選擇除具有特定類的鏈接之外的所有鏈接

CSS

.foot_active { 
    text-decoration:underline; 
} 
.foot_inactive { 
    text-decoration:none; 
} 

HTML

<div class="sitemap"> 
    <table class="table_site"> 
     <tr> 
      <td class="subsite"><a>op1</a></td> 
      <td class="subsite"><a>op2</a></td> 
      <td class="subsite"><a>op3</a></td> 
     </tr> 
    </table> 
</div> 

腳本

$('a:contains("op1")') 
    .live('click', function(){ 
     $(this).addClass('foot_active'); 
     $('a:not(.foot_active)').addClass('foot_inactive'); 
    }); 
$('a:contains("op2")') 
    .live('click', function(){ 
     $(this).addClass('foot_active'); 
     $('a:not(.foot_active)').addClass('foot_inactive'); 
    }); 
$('a:contains("op3")') 
    .live('click', function(){ 
     $(this).addClass('foot_active'); 
     $('a:not(.foot_active)').addClass('foot_inactive'); 
    }); 

這個腳本只適用於第一次的鏈接點擊,而不是未來的點擊。 我覺得我做錯了什麼,但現在我的大腦似乎很生氣。

謝謝。

回答

1

爲TD裏面的所有鏈接與類稱爲.sitemap你可以嘗試:

$('.sitemap a') .live('click', function(){ 
    $(this).addClass('foot_active'); 
    $('.sitemap a').not(this).removeClass('foot_active'); 
}); 
0

你可以試試...

$('a.foot_active').removeClass('foot_active').addClass('foot_inactive'); $(this).removeClass('foot_inactive').addClass('foot_active');

...這是否你想要什麼?

2

你永遠不會刪除任何類,所以你最終會得到所有具有非活動類的鏈接。

實際上,您根本不需要非活動類,只需刪除活動類即可。這將取代你的三個事件處理程序:

$('a') .live('click', function(){ 
    $(this).addClass('foot_active'); 
    $('a').not(this).removeClass('foot_active'); 
}); 

你可能想使用一個更具體的selctor比'a',像'.subsite a'如果你有網頁中的任何鏈接越多。

0

您不想更改所有其他元素。一個元素可以有很多類,所以你只需要切換活動類。

$('.table_site a').addClass('foot_inactive').click(function(){ 
    $('.foot_active').removeClass('foot_active'); 
    $(this).addClass('foot_active');  
}) 
1

首先,因爲它是在jQuery的1.7不贊成你不應該使用.live()

這是你在找什麼,我希望。

$('.sitemap a').click(function(){ 
    $('.sitemap a').toggleClass('foot_inactive',true).toggleClass('foot_active',false); 
  $(this).addClass('foot_active');     
}); 
相關問題