CodeIgniter教程:添加S & CSS
在CodeIgniter中添加JavaScript和CSS文件非常简单,你只需在根目录下创建JS和CSS文件夹,并复制所有的js文件和css文件夹中到其中即可。
我们假设你已经创建了一个sample.js和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文件,在文件末尾添加以下内容为上述控制器添加路由。
$route['profiler'] = "Profiler_controller"; $route['profiler/disable'] = "Profiler_controller/disable"
在浏览器中使用下面的URL来执行上面的例子。
http://yoursite.com/index.php/test