【问题标题】:How to properly use $this->uri->segment(n) Setting a class as active in navigation using codeigniter如何正确使用 $this->uri->segment(n) 使用 codeigniter 将类设置为在导航中处于活动状态
【发布时间】:2017-03-15 09:59:34
【问题描述】:

似乎我在代码中遗漏了一些东西。我正在尝试将 uri 段用于导航中的活动菜单。感谢您的帮助,我对 CodeIgniter 还很陌生,非常感谢。

PHP:

    <a href="<?php echo base_url('home/co_landing_page');?>" 
        <?php 
          if($this->uri->segment(1)=="home/co_landing_page")
          {echo 'class="nav_active"';}
        ?>
    >Home</a>
    <a href="<?php echo base_url('home/co_profile');?>" 
        <?php 
          if($this->uri->segment(1)=="home/co_profile")
          {echo 'class="nav_active"';}
        ?>
    >Profile</a>

CSS:

a.nav_active{
    color:#4f91a2;
    font-size: 50px;
}

控制器:

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends CI_Controller {

    public function index()
    {
        $this->load->view('landing_page');
    }

    function co_landing_page(){ $this->load->view('landing_page');}
    function co_project(){ $this->load->view('project');}
    function co_profile(){ $this->load->view('profile');}
}

【问题讨论】:

标签: php codeigniter


【解决方案1】:

请试试这个

<a href="<?php echo base_url('home/co_landing_page');?>" class="<?php echo ($this->uri->segment(2) == 'co_landing_page')?'nav_active':''; ?>  >Home</a>
<a href="<?php echo base_url('home/co_profile');?>" class="<?php echo ($this->uri->segment(2) == 'co_profile')?'nav_active':''; ?>  >Profile</a>

以后请阅读这些链接以更好地理解https://stackoverflow.com/a/19293943/3568847https://www.codeigniter.com/user_guide/libraries/uri.html?highlight=uri

【讨论】:

  • @Philip 欢迎您,我们都在这里为您提供帮助。好吧,不需要单个控制器,但如果您愿意或需要,您可以使用 $this-&gt;uri-&gt;segment(1) == 'home' &amp;&amp; $this-&gt;uri-&gt;segment(2) == 'co_landing_page'
  • 哦,我明白了,再次感谢@Praveen Kumar
【解决方案2】:

做简单的方法。在您的 HTML 中为您的部分或 div 提供标识符

<div class="slider" id="welcome-sec">

在你的链接中使用like

<a href="<?php echo base_url()?>/controller/function#welcome-sec">

您将被重定向到页面的该部分。

Example

【讨论】:

  • 它已经重定向到另一个页面。选择菜单时,我需要在课堂上设置一个活动。顺便谢谢。
【解决方案3】:

尝试使用uri_string() 代替uri_segment。 uri_strig() 返回一个带有complete URI 的字符串。

如果你有full URL:

http://example.com/home/co_landing_page

该方法将返回:

home/co_landing_page

所以试试下面:

<a href="<?php echo base_url('home/co_landing_page');?>" 
        <?php 
          if($this->uri->uri_string() =="home/co_landing_page")
          {echo 'class="nav_active"';}
        ?>
    >Home</a>
    <a href="<?php echo base_url('home/co_profile');?>" 
        <?php 
          if($this->uri->uri_string() =="home/co_profile")
          {echo 'class="nav_active"';}
        ?>
    >Profile</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 2019-03-24
    • 1970-01-01
    • 2013-08-15
    相关资源
    最近更新 更多