2

我正在尝试一种更易于维护的方式来构建我的代码,正如 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>
4

3 回答 3

4

尝试将 a 加载view到主view

/application/controllers/test.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);
  }
}

/application/views/test.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>
于 2013-10-01T21:11:48.443 回答
1

我认为没有办法围绕脚本制作条件“if”语句,所以我在我的问题中使用了建议的解决方案。

检查标题以查看它是否是所需的页面:

<?php if($title = "Photo Albums - Hands of Humanity"):?>

然后将脚本添加到 DOM(如果是):

<script>
$(document).ready(function() {

//jquery stuff

});
</script>
<?php endif;?>

如果有其他更好的可维护性方法,我会很高兴听到它们

于 2013-10-01T20:39:11.833 回答
1

您可以指定 JS 作为传递给视图的数据的一部分:

控制器1

$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>';
}
于 2013-10-01T20:24:29.633 回答