0

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

JS 斌: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>
4

2 回答 2

5

它正在开火,因为你马上就打电话给它!

所以你要:

aboutButton.onclick = function(){showPanel(aboutPanel);};
于 2013-01-29T20:55:18.917 回答
3

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

绑定事件的代码应该是:

aboutButton.onclick = showPanel;
于 2013-01-29T20:54:29.147 回答