Codeigniter:如果current_url()== href,添加一个类来链接

时间:2012-02-28 10:47:25

标签: codeigniter

您是否了解如何使用javascript检查current_url()是否等同于链接的href 而不使用?这样做时,如果href相同,则将class="active"添加到链接。

编辑:首先想到的是制作一个包含所有href值的数组,然后使用foreach来比较每个值,但也许你有比这更好的方法?

回答 Nick 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>';
    }
}

1 个答案:

答案 0 :(得分: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>';
    }
}

我没有测试过这个,所以请查看bug。像这样调用锚函数:

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

请参阅有关如何扩展帮助程序的文档:http://ellislab.com/codeigniter/user_guide/general/helpers.html

编辑:确定我已经对其进行了测试并更新了我的答案,因此现在应该可以正常使用。

相关问题