doudaotui4297
2016-03-16 15:58
浏览 52
已采纳

如何在CodeIgniter的视图中使用这个看似简单的循环?

In the view, right before the footer, I want to load three JavaScript files. So, the controller sets three variables. For example, $js_1 = "bootstrap.js", $js_2 = '' and $js_3 = "tinymce.js", which may or may not be empty. The logic is, it should echo only if the variable is not empty. I also want to use the ternary if operator.

This was the best I could try.

for ($i = 1; $i <= 3; $i++)
{
    echo (!empty ('$js_' . $i)) ? get_jscript('$js_' . $i) : NULL;
}

The function get_jscript() simply returns the HTML script src.

function get_jscript($js) 
{
    return '<script type="text/javascript" src="' . $js . '"></script> ';
}

Please note that I intend to ask this question to primarily learn the correct PHP syntax and not just load JS in the view.

图片转代码服务由CSDN问答提供 功能建议

视图中,就在页脚之前,我想加载三个JavaScript文件。 因此,控制器设置三个变量。 例如,$ js_1 =“bootstrap.js”,$ js_2 =''和$ js_3 =“tinymce.js”,可能为空,也可能不为空。 逻辑是,只有当变量不为空时才应该回显。 我还想使用三元if运算符

这是我能尝试的最好的。

   for($ i = 1; $ i&lt; = 3; $ i ++)
 {
 echo(!empty('$ js_'。$ i))?  get_jscript('$ js_'。$ i):NULL; 
} 
   
 
 

函数get_jscript()只返回HTML脚本src。 \ n

  function get_jscript($ js)
 {
 return'&lt; script type =“text / javascript”src =“'。$ js。'”&gt;&lt; / script&gt;  '; 
} 
   
 
 

请注意,我打算提出这个问题,主要是学习正确的PHP语法,而不仅仅是在视图中加载JS。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duangu1878 2016-03-16 16:08
    已采纳

    This has some great info on how to use variable variables.

    for ($i = 1; $i <= 3; $i++)
    {
        echo (!empty (${'js_'.$i})) ? get_jscript(${'js_'.$i}) : NULL;
    }
    
    点赞 评论
  • dsgdhtr_43654 2016-03-16 16:12

    if you can create a array like this->

    $javascript = array('js_1' => "bootstrap.js", 'js_2' => '', 'js_3' = "tinymce.js");
    

    then in your view you have to just call a method

    loop_javascript($javascript);
    

    it's better to create a function in codeigniter helper and call that helper in controller's function (check how to use helpers in codeingiter) https://ellislab.com/codeigniter/user-guide/general/helpers.html->

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    if ( ! function_exists('loop_javascript'))
    {
        function loop_javascript($jscript_array)
        {
            foreach($jscript_array as $key =>$value){
                if($value != ''){
                    echo '<script type="text/javascript" src="' . $value. '"></script>';
                }
            }
        }   
    }
    
    点赞 评论
  • douyousu9691 2016-03-16 16:24
    for ($i = 1; $i <= 3; $i++)
    {
        if(!empty($js.'_'.$i)){ echo get_jscript($js.'_'.$i); echo "</br>";}
    }
    
    function get_jscript($js) 
    {
        return '<script type="text/javascript" src="' . $js . '"></script> ';
    }
    
    点赞 评论

相关推荐 更多相似问题