从PHP echo创建的Javascript函数在一种情况下工作但不在另一种情况下工作

时间:2017-07-27 16:42:57

标签: javascript php html

我的函数传递一个字符串,而字符串又是命名脚本中使用的变量的基础。最终目标是打印出给定的字符串,并显示三个可点击的图标,其下方有一个计数器,点击量增加。

第一个图标效果很好。其余两个导致

  

“Uncaught TypeError:de1Door不是HTMLElement.onclick(test.php:60)中的函数”。

icon1的相同逻辑应用于此图标,浏览器中的源代码看起来很好。你们有什么想法吗?

<?php

/* Takes one param and uses it as basis to make unique variables
*  later to be stored in database.
*  Echos out the param with three following icons.
*  The icons are clickable and doing so will increase the counter displayed underneath.
*/
function someFunction($name){

    // Light icon
    $light = "$name" . "Light";
    $lightCounter = "$name" . "LightCounter";

    // Door icon
    $door = "$name" . "Door";
    $doorCounter = "$name" . "DoorCounter";

    // Window icon
    $window = "$name" . "Window";
    $windowCounter = "$name" . "WindowCounter";

    // Creates the clickable icons for HTML
    echo "<div class='w3-container w3-center w3-cell-row w3-green'>
        <div class='w3-cell'>
            <h1>$name</h1>
        </div>  
        <div class='w3-cell'>
            <i class='fa fa-lightbulb-o w3-jumbo' onClick='$light()'></i>
            <h3><a id='$light'>0</a></h3>
        </div>
        <div class='w3-cell'>
            <i class='fa fa-windows w3-jumbo' onClick='$door()'></i>
            <h3><a id='$door'>0</a></h3>
        </div>
        <div class='w3-cell'>
            <i class='fa fa-lock w3-jumbo' onClick='$window()'></i>
            <h3><a id='$window'>0</a></h3>
        </div>
        </div>
        ";

        // Creates the javascript that handles click on icons
        echo "<script type='text/javascript'>

                var $lightCounter = 0;
                function $light() {
                    $lightCounter += 1;
                    document.getElementById('$light').innerHTML = $lightCounter;
                }

                var $doorCounter = 0;
                function $door() {
                    $door += 1;
                    document.getElementById('$door').innerHTML = $doorCounter;
                }

                var $windowCounter = 0;
                function $window() {
                    $window += 1;
                    document.getElementById('$window').innerHTML = $windowCounter;
                }

                </script>
                ";

}//myFunction end

?>

1 个答案:

答案 0 :(得分:0)

在您的门窗功能中,您有$door += 1;(对于窗口分别相同),$door应该是$doorCounter$window$windowCounter