2013-02-26 163 views
0

美好的一天。檢查是否使用jQuery選擇ID

我使用jQuery的下面點擊功能

$(function() { 

      $("#areas ul a").click(function (event) { 
       event.preventDefault(); 
       $("#areas ul li a").removeClass('activeAreas'); 
       $(this).addClass('activeAreas'); 
       $(".hidden").hide(200); 
       $($(this).attr("href")).show(500) 

      }); 

     }); 

什麼,我想要做的就是在這個循環什麼,要檢查特定元素是否處於活動狀態,然後採取行動時說:

例如。

$("#areas ul a").click(function (event) { 
       event.preventDefault(); 
       $("#areas ul li a").removeClass('activeAreas'); 
       $(this).addClass('activeAreas'); 
       $(".hidden").hide(200); 
       $($(this).attr("href")).show(500) 

       //I'm adding this... but it is not working 

       if($(this).attr(href) = 'pretoriaDetail'){ 
        alert('it works'); 
       } 

      }); 

我如何得到,如果聲明工作......?

感謝

+0

什麼叫主動是什麼意思? – dakait 2013-02-26 07:55:51

+5

我假設你樣本中的'='是一個錯字。它應該是'=='。而if條件中的href應該是「href」。代碼適用於我這個小提琴:http://jsfiddle.net/Qr5nL/ – ryadavilli 2013-02-26 07:56:02

+0

'if($ .trim($(this).attr(href))=='#pretoriaDetail')alert('ok') ;' – adeneo 2013-02-26 08:00:39

回答

2

如果你想檢查是否class被應用到DOM然後.hasClass會有所幫助。

公文http://api.jquery.com/hasClass/

還有一件事沒有錯誤代碼。

if($(this).attr(href) = 'pretoriaDetail'){ 
      alert('it works'); 
} 

必須

if($(this).attr("href") == 'pretoriaDetail'){ 
      alert('it works'); 
} 

因爲什麼=做而==比較它與HREF必須用引號包圍被分配值了這一點。

+1

不只是代碼中的'=''href'也應該用這樣的引號:'$(this).attr('href')' – Jai 2013-02-26 08:05:15

+0

@Jai嘿朋友,我已經在回答中定義了它...看起來... – 2013-02-26 08:05:40

+1

是我的壞只是看到它。 – Jai 2013-02-26 08:06:27

0

我想你應該試試這個:

var ID = $(this).attr("href"); 

$('#'+ID).show(500); 

Declare a variable and use it as an id.

那麼這應該是這樣的:

 $(function() { 
     $("#areas ul a").click(function (event) { 
      var ID = $(this).attr("href"); 
      event.preventDefault(); 
      $("#areas ul li a").removeClass('activeAreas'); 
      $(this).addClass('activeAreas'); 
      $(".hidden").hide(200); 
      $('#'+ID).show(500); // or this way $('[id="'+ID+'"]').show(500); 
     }); 
    }); 
1
$(function() { 
     $("#areas ul a").click(function (event) { 
      event.preventDefault(); 
      if(!$(this).hasClass('activeAreas')){ 
       $("#areas ul li a").removeClass('activeAreas'); 
       $(this).addClass('activeAreas'); 
       $(".hidden").hide(200); 
       $($(this).attr("href")).show(500); 
      } 
     }); 

    }); 
相關問題