防止类似的PHP包含文件同时执行

时间:2018-01-01 07:17:43

标签: javascript php

我有以下三个文件:

index.php
menu.php
move.js

在index.php中,我有2个相似的数字,具有相同的标题。我把标题包含在menu.php文件中。在标题中,有一个按钮“ClickMe”。我打算做的是每当按下按钮时,另一个div应该向右移动,文本变为“Changed Text”,然后当再次单击该按钮时,div应该移回中心并且文本变为“Original”文本”。当我将menu.php包含在index.php中一次时,一切正常。但是当我再次添加menu.php时,div会向右移动并在我按下按钮时返回到中心。

有没有办法阻止javascript监听器多次执行,同时在index.php文件中多次包含同一个文件?

这是我的代码:

的index.php

 //...................
        <figure class="front">
             <?php include ("menu.php"); ?>               
        </figure>
        <figure class="back">
             <?php include ("menu.php"); ?>
        </figure>
    //..........................

menu.php

//...........
<button id="mover" type="button" >ClickMe</button>
<script type="text/javascript" src="js/move.js"></script>

move.js

//moves the figure to the right when clicked, and returns it to the center when clicked again
var collapsed = false;

$('#mover').on('click', function () {

    if (collapsed) {
        console.log("true");
        $("#container").animate({
            left: 0
        }, "slow", function () {

            $('#mover').html('Original text');
        });

        collapsed = false;

    } else {
        console.log("false");
        $("#container").animate({
            left: '25%'
        }, "slow", function () {

            $('#mover').html('Changed text');
        });

        collapsed = true;
    }
});

2 个答案:

答案 0 :(得分:2)

主要的问题是,包括menu.php两次,你创建两个具有相同ID&#34; mover&#34;的HTML元素,这是开始时无效的HMTL,但也意味着JS包括两次,会同时触发它们。

您可能希望重新构建应用程序,将JS分开并仅包含一次,并为&#34; front&#34;创建具有不同ID的按钮。和&#34;回来&#34;。

答案 1 :(得分:1)

可能有JS解决方法可以获得类似于Php&#39; include_once&#39;对于JS资产。

以下是基于Php的独特导入JS资产的方法:

<?php

class JsImporter
{
    public $srcs = [];

    public function importOnce($src)
    {
        if(!in_array($src, $this->srcs))
            $this->srcs[] = $src;
    }

    public function __toString()
    {
        $o = "\n";
        foreach($this->srcs as $src)
            $o.= '<script type="text/javascript" src="' . $src . '"></script>';

        return $o . "\n";
    }
}

$jsImporter = new JsImporter;

?>
<html>
<body>

    <!-- this code in include -->
    <button>Click Me</button>
    <?php $jsImporter->importOnce('thing.js'); ?>

    <!-- this code in include -->
    <button>Click Me</button>
    <?php $jsImporter->importOnce('thing.js'); ?>

    <?= $jsImporter; // output script elements at footer. ?>

</body>
</html>

这将在html正文的底部插入一个脚本元素。

(如果您要重复html块,请确保不要重复元素ID。)