我正在尝试一种更易于维护的方式来构建我的代码,正如nettuts+的一些教程所学到的那样。
我成功地将页眉和页脚文件与每个页面的主要内容分开,以便它们与每个不同的页面一起加载,从而更轻松地管理对这两个文件的更改。
我目前只想在我的页脚中添加一些 jQuery 代码,只为一页。这就是我在思考中碰壁的地方。如何允许此 jQuery 代码仅存在于页脚中,而不是所有页面?有人可以解释一下吗?
我正在考虑做这样的事情:
<?php if($title = "The jQuery Page"){?>
<script>
jquery code here....
</script>
<?php } ?>
但我认为这被认为是混乱的,因为你正在使用一种语言来衬托另一种语言。
编辑:这是请求的代码:
在我的控制器中,我调用视图:
$data['title'] = "The jQuery Page";
$this->load->view('header', $data);
$this->load->view('cool_page');
$this->load->view('footer');
然后在我的页脚中,我只想在这个页面页脚中加载一个特定的脚本:
<script src="<?php echo base_url();?>js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
/*cool jquery stuff*/
});
</script>
尝试将view
加载到主view
应用程序/控制器/测试.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test extends CI_Controller {
public function index() {
$data = array(
'title' => "The jQuery Page",
'script' => TRUE // if you omit or comment this variable the 'views/script.php' is not loaded
);
$this->load->view('test', $data);
}
}
/应用程序/视图/测试.php
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<?php if (isset($script)) { $this->load->view('script'); } ?>
</body>
</html>
/application/views/script.php
<script>
jquery code here....
</script>
您可以指定 JS 作为传递给视图的数据的一部分包含在内:
CONTROLLER1
$this->data['js'][] = 'alert(''Hi'');';
$this->data['js'][] = 'alert(''Hey'');';
$this->load->view('footer', $this->data);
CONTROLLER2
$this->data['js'][] = 'alert(''Yo'');';
$this->data['js'][] = 'alert(''Sup'');';
$this->load->view('footer', $this->data);
页脚视图
if(isset($js) && is_array($js) && count($js) > 0){
echo '<script>';
foreach($js as $key=>$value){
$value;
}
echo '</script>';
}
我认为没有办法围绕脚本进行条件的"if"语句,所以我在我的问题中使用了建议的解决方案。
检查标题以查看它是否是所需的页面:
<?php if($title = "Photo Albums - Hands of Humanity"):?>
如果是这样,则将脚本添加到 DOM:
<script>
$(document).ready(function() {
//jquery stuff
});
</script>
<?php endif;?>
如果还有其他方法对可维护性更好,我将很高兴听到它们