javascript
  • jquery
  • window.location
  • 2014-10-01 41 views 0 likes 
    0

    有沒有一種方法來測試您的當前URL位置是否與頁面上的鏈接匹配,並且還檢查匹配的鏈接是否具有特定的div類?當前的URL和鏈接匹配 - 與div類檢查

    例如

    jQuery(document).ready(function($){  
    
    // find a-href on page with matching current location URL 
    jQuery("*").find("a[href='"+window.location.href+"']").each(function(){ 
    
        // if matching a-href contains class .aaa 
        // then BBB action 
    
        // else if matching a-href contains class .bbb 
        // then CCC action 
    
    })}); 
    
    +0

    使用hasClass('aaa')。 – SSA 2014-10-01 14:15:06

    回答

    2

    不確定:

    jQuery(document).ready(function(){  
    
        // find a-href on page with matching current location URL 
        jQuery("a[href='"+window.location.href+"']").each(function(){ 
    
         if ($(this).hasClass('aaa')) { 
          // BBB 
         } 
    
         if ($(this).hasClass('bbb')) { 
          // CCC 
         } 
        }); 
    
    }); 
    

    修改您的代碼:刪除不必要jQuery("*")加上find,併除去$作爲參數。 (在意見建議處)

    +1

    是不是使用'*'昂貴?你可以直接使用選擇器'a [href ='「+ window.location.href +」']'而不使用'.find()':) – Terry 2014-10-01 14:17:16

    +0

    @Terry haha​​h真的,原來的jquery很殘酷,我會編輯:p – michaelb 2014-10-01 14:18:09

    +0

    爲什麼你將'$'傳遞給函數?在這種情況下沒有必要。你正在將jquery傳遞給一個多餘的jquery函數。 – 2014-10-01 14:50:11

    相關問題