2012-02-28 115 views
1

你知道一種方法如何檢查是否current_url()相當於一個鏈接的href 沒有使用JavaScript?這樣做,如果href是相同的,然後將class="active"添加到鏈接。Codeigniter:添加一個類來鏈接如果current_url()== href

編輯:該想到的第一件事是讓然後用foreach到每一個比較,但也許你有比這更好的方式,所有的href值的數組?

回答感謝尼克Pyett

if(!function_exists('anchor')){ 
    function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE){  
     if(!is_array($uri)){ 
      $site_url = (!preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri; 
     } 
     else { 
      $site_url = site_url($uri); 
     } 

     $title = (bool)$title ? $title : $site_url; 
     if($attributes != '') $attributes = _parse_attributes($attributes); 
     $active = $uri == uri_string() && $apply_active ? ' class="'.$apply_active.'"' : NULL; 

     return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>'; 
    } 
} 
+0

你用什麼來產生你的鏈接?看法?模板? – Joseph 2012-02-28 10:49:33

+0

我正在使用Views。 – enchance 2012-02-28 10:53:29

回答

1

你可以擴展的URL助手這樣的錨功能。

if (! function_exists('anchor')) 
{ 
    function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE) 
    { 
     $title = (string) $title; 

     if (! is_array($uri)) 
     { 
      $site_url = (! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri; 
     } 
     else 
     { 
      $site_url = site_url($uri); 
     } 

     if ($title == '') 
     { 
      $title = $site_url; 
     } 

     if ($attributes != '') 
     { 
      $attributes = _parse_attributes($attributes); 
     } 

     if ($uri == uri_string() AND $apply_active) 
     { 
      $active = ' class="'.$apply_active.'"'; 
     } 
     else $active = NULL; 

     return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>'; 
    } 
} 

我還沒有測試過,所以請檢查一下錯誤。調用錨功能是這樣的:

anchor('my_page', 'My Page', '', 'active'); 

請參閱如何延長助手文檔:http://ellislab.com/codeigniter/user_guide/general/helpers.html

編輯: OK我測試過它,並更新了我的答案,因此現在應該很好地工作。

+0

這很好用。在回家的路上,我已經想過自己擴展anchor(),但看起來像你打敗了我。我所做的就是使用三元運算符縮短代碼以節省空間。我將在上面發佈您的代碼,以便大家可以輕鬆看到它。 – enchance 2012-02-28 13:00:44