CodeIgniter - 添加JS和CSS

在CodeIgniter中添加JavaScript和CSS(层叠样式表)文件非常简单.你必须在根目录中创建JS和CSS文件夹,并复制JS文件夹中的所有.js文件和CSS文件夹中的.css文件,如图所示.

添加JS和CSS

例如,我们假设您创建了一个JavaScript文件 sample.js 和一个CSS文件 style.css .现在,要将这些文件添加到您的视图中,请在控制器中加载URL帮助程序,如下所示.

$this->load->helper('url');

在控制器中加载URL帮助器后,只需在视图文件中添加以下给定的行,即可加载sample.js和style.css文件.查看如下所示.

<link rel = "stylesheet" type = "text/css" 
   href = "<?php echo base_url(); ?>css/style.css">

<script type = 'text/javascript' src = "<?php echo base_url(); 
   ?>js/sample.js"></script>

示例

创建名为 Test.php 的控制器并将其保存在 application/controller/Test.php

<?php 
   class Test extends CI_Controller {
	
      public function index() { 
         $this->load->helper('url'); 
         $this->load->view('test'); 
      } 
   } 
?>

创建名为 test.php 的视图文件并将其保存在 application/views/test.php

<!DOCTYPE html> 
<html lang = "en">
 
   <head> 
      <meta charset = "utf-8"> 
      <title>CodeIgniter View Example</title> 
      <link rel = "stylesheet" type = "text/css" 
         href = "<?php echo base_url(); ?>css/style.css"> 
      <script type = 'text/javascript' src = "<?php echo base_url(); 
         ?>js/sample.js"></script> 
   </head>
	
   <body> 
      <a href = 'javascript:test()'>Click Here</a> to execute the javascript function. 
   </body>
	
</html>

创建名为 style.css 的CSS文件并将其保存在 css/style.css

body { 
   background:#000; 
   color:#FFF; 
}

创建一个名为 sample.js 的JS文件,并将其保存在 js/sample.js

function test() { 
   alert('test'); 
}

更改 application/config/routes.php  routes.php 文件>为上述控制器添加路线,并在文件末尾添加以下行.

$route['profiler'] = "Profiler_controller"; 
$route['profiler/disable'] = "Profiler_controller/disable"

在浏览器中使用以下URL执行上述示例.

 http://yoursite.com/index.php/test