onclick事件即使没有点击也是如此

时间:2013-01-29 20:51:19

标签: javascript

即使没有点击,我的onclick事件也会被触发。我不知道为什么?以下是我的代码。主页面板应首先加载,当用户单击aboutButton时,应将它们带到about面板。

JS Bin:http://jsbin.com/alebox/1/edit

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>

function myOnloadFunc() {

    var homePanel = document.getElementById("homePanel");
    var aboutPanel = document.getElementById("aboutPanel");
    var settingsPanel = document.getElementById("settingsPanel");
    var gamePanel = document.getElementById("gamePanel");
    var resultsPanel = document.getElementById("resultsPanel");

    // All panels in app
    var panels = [homePanel, aboutPanel, settingsPanel, gamePanel, resultsPanel];


    // Show selected panel and hide all other panels
    function showPanel(panel) {
        for (var i = 0; i < panels.length; i++) {
            if (panels[i] === panel) {
                // Show panel
                // this referred to global object, i.e. window
                panels[i].style.display = "block";
            } else {
                // Hide
                panels[i].style.display = "none";
            }
        }
    }

    showPanel(homePanel);

    // CODE THAT IS GIVING ME A PROBLEM /////////////////////////
    var aboutButton = document.getElementById("aboutButton");

    aboutButton.onclick = showPanel(aboutPanel);
    // CODE THAT IS GIVING ME A PROBLEM /////////////////////////
}

window.onload = myOnloadFunc;
</script>

</head>

<body>
<!-- homePanel -->
<div class="panel" id="homePanel">
<div align="center">
<p><strong>Web App</strong></p>
<p><a id="playButton">Play</a> &nbsp;&nbsp;&nbsp; <a id="aboutButton">About</a></p>
</div>
</div>

<!-- aboutPanel -->
<div class="panel" id="aboutPanel">
About panel
</div>

<!-- settingsPanel -->
<div class="panel" id="settingsPanel">
Settings panel
</div>

<!-- gamePanel -->
<div class="panel" id="gamePanel">
Game panel
</div>

<!-- resultsPanel -->
<div class="panel" id="resultsPanel">
Results panel
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:5)

因为你正在立即召唤它而被解雇了!

所以你想要:

aboutButton.onclick = function(){showPanel(aboutPanel);};

答案 1 :(得分:2)

要将函数附加到事件,只应给出对函数的引用。在使用()时,您实际上正在调用该函数。

绑定事件的代码应为:

aboutButton.onclick = showPanel;