是否可以禁用JavaScript文件在PHP脚本中显示?

时间:2016-10-03 19:26:29

标签: javascript php

我想在PHP中进行配置,以便他们可以禁用或启用某个JavaScript(外部)在另一个PHP脚本中显示,我该怎么做呢?

例如

的config.php

<?php
$javascript = enabled; /*Means js will display in html file; if it says disabled then it won't*/
?>

如果启用了javascript,它将显示脚本:

<script src="bkcHANGE.js"></script>

2 个答案:

答案 0 :(得分:0)

在你的config.php

<?php
  $javascript_enabled = true;
?>

在你看来

<?php if ($javascript_enabled): ?>
  <script src="bkcHANGE.js"></script>
<?php endif; ?>

答案 1 :(得分:0)

最简单的方法:

<?php
if($javascript === 'enabled') {
    ?>
    <script src="foo.js"></script>
    <?php
}
?>

如果你想以有效的方式对某些脚本做同样的事情,那会更复杂一点,这是我使用OOP做到这一点的方法:

<?php
class Script {
    public $enabled = true;
    public $script_name;

    function __construct($enabled, $name) {
        $this->enabled = $enabled;
        $this->script_name = $name . '.js';
    }
}

class ScriptControl {
    private $scripts = [];

    function __construct(array $scripts) {
        $this->scripts = $scripts;
    }

    function useScripts() {
        foreach($this->scripts as $s) {
            if($s->enabled) {
                ?>
                <script src="<?php echo $s->script_name; ?>"></script>
                <?php
            }   
        }
    }
}

//Example:
$scripts = [new Script(true, "foo"),new Script(false, "bar")];

$scriptcontrol = new ScriptControl($scripts);

$scriptcontrol->useScripts();
?>