我正在尝试一种更易于维护的方法来构建我的代码,正如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>
答案 0 :(得分:4)
尝试将view
加载到主view
<?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);
}
}
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<?php if (isset($script)) { $this->load->view('script'); } ?>
</body>
</html>
<script>
jquery code here....
</script>
答案 1 :(得分:1)
您可以指定JS作为传递给视图的数据的一部分包含:
<强> CONTROLLER1 强>
$this->data['js'][] = 'alert(\'Hi\');';
$this->data['js'][] = 'alert(\'Hey\');';
$this->load->view('footer', $this->data);
<强>控制器2 强>
$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>';
}
答案 2 :(得分:1)
我认为围绕脚本制作条件'if'语句并不存在,所以我在我的问题中使用了建议的解决方案。
检查标题以查看它是否是所需的页面:
<?php if($title = "Photo Albums - Hands of Humanity"):?>
然后将脚本添加到DOM中,如果是这样的话:
<script>
$(document).ready(function() {
//jquery stuff
});
</script>
<?php endif;?>
如果有其他方法可以提高可维护性,我很乐意听到它们