Javascript functions are being called all at once

时间:2015-06-15 14:44:09

标签: javascript php

The purpose of my code is to randomly display four icons and depending on which one the user clicks on, a small amount of text will be appended to a text file. My problem is that, after an icon is clicked on, all four of the functions are called which writes to the txt file four times. How can I get it so that only the correctly corresponding function is called.

    <div style="text-align:center" "padding-left: 60px">
        <form action="(im hiding the URL)construct/index.html" id="formid" onclick= function() {myFunction()}>
            <form>

            </form>
        </form>
    </div>

    <script>
        document.getElementById("icon_1.png").onclick = function writeTo1(){
            <?php
                $file = fopen("icon_select.txt","a");
                echo fwrite($file,"-Icon 1-");
                fclose($file);
            ?>  
        }
        document.getElementById("icon_2.png").onclick = function writeTo2(){
            <?php
                $file = fopen("icon_select.txt","a");
                echo fwrite($file,"-Icon 2-");
                fclose($file);
            ?>  
        }
        document.getElementById("icon_3.png").onclick = function writeTo3(){
            <?php
                $file = fopen("icon_select.txt","a");
                echo fwrite($file,"-Icon 3-");
                fclose($file);
            ?>  
        }
        document.getElementById("icon_4.png").onclick = function writeTo4(){
            <?php
                $file = fopen("icon_select.txt","a");
                echo fwrite($file,"-Icon 4-");
                fclose($file);
            ?>  
        }
    </script>

1 个答案:

答案 0 :(得分:0)

在我看来,当请求页面时,4位PHP正在运行,因此在那时添加到文本文件中。然后当JavaScript运行时函数为空,因此它没有任何效果。检查浏览器中的页面源以查看浏览器的功能以及页面加载后但在单击图标之前检查文本是否已添加到文件中。