Javascript:onLoad函数无意中激活了我的EventListener

时间:2015-07-20 04:27:09

标签: javascript html

我不知道为什么,但是我的onLoad函数激活了我的所有函数,而没有实际点击按钮。提前致谢。我似乎也难以将javascript放入反引号中。所以javascript在JsFiddle

HTML:

<title>Jake's Game</title>
<link rel="icon" href="iconname.gif" type="image/gif">
<body>
<div class="WhiteBackground">
    <div id="Input" class="center">
        <p>Player 1</p>
        <input type="text" id="Name1">
        <br>
        <p>Player 2</p>
        <input type="text" id="Name2">
        <br>
        <p>Player 3</p>
        <input type="text" id="Name3">
        <br>
        <p>Player 4</p>
        <input type="text" id="Name4">
        <br>
        <button id="StartGame">Start Game</button>
    </div>
    <div align="center">
        <p id="Turn"></p>
        <table>
            <tr>
                <th></th>
                <th id="Player1">Player 1</th>
                <th id="Player2">Player 2</th>
                <th id="Player3">Player 3</th>
                <th id="Player4">Player 4</th>
                <th>Shop</th>
            </tr>
            <tr>
                <td>Gold</td>
                <td id="Gold1"></td>
                <td id="Gold2"></td>
                <td id="Gold3"></td>
                <td id="Gold4"></td>
                <td>
                    <button id="NoBuy">N/A</button>
                </td>
            </tr>
            <tr>
                <td>Miners</td>
                <td id="Miners1"></td>
                <td id="Miners2"></td>
                <td id="Miners3"></td>
                <td id="Miners4"></td>
                <td>10000 Gold</td>
            </tr>
            <tr>
                <td>Wood</td>
                <td id="Wood1"></td>
                <td id="Wood2"></td>
                <td id="Wood3"></td>
                <td id="Wood4"></td>
                <td>
                    <button id="NoBuy">N/A</button>
                </td>
            </tr>
            <tr>
                <td>Loggers</td>
                <td id="Loggers1"></td>
                <td id="Loggers2"></td>
                <td id="Loggers3"></td>
                <td id="Loggers4"></td>
                <td>10000 Gold</td>
            </tr>
        </table>
        <button id="EndTurn">End Turn</button>
    </div>
</div>
</body>

的jsfiddle: https://jsfiddle.net/steventang166/gtb74bpr/41/

1 个答案:

答案 0 :(得分:0)

交配,当你绑定事件时,有一个错误,这样做:

 document.getElementById("StartGame").addEventListener("click", StartGame);
document.getElementById("NoBuy").addEventListener("click", NoBuy);
document.getElementById("EndTurn").addEventListener("click", EndTurn);

当你在javascript中执行'()'时,它意味着现在就执行此函数,这在某些情况下可以像自我初始化对象一样方便:

(function(){/* do something */})