0

我正在尝试布局 Web 应用程序。我的网络应用程序的每个屏幕都是一个面板。我现在有以下面板:主页、关于、设置、游戏和结果。我只想一次显示一个面板。现在只有主面板应该显示,但我的代码不起作用(所有面板现在都显示)。我错过了什么?

jsFiddle:http: //jsfiddle.net/bNzVA/

<!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>
<style>
</style>
<script>
window.onload = myOnloadFunc;

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 (panel) {
                // Show panel
                this.style.display = "block";
            } else {
                // Hide
                this.style.display = "none";
            }
        }
    }

    showPanel("homePanel");
}
</script>
</head>

<body>
<!-- homePanel -->
<div class="panel" id="homePanel">
Home panel
</div>

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

<!-- 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

1 回答 1

1

您在代码中有几个问题。

  1. this关键词。您使用它的方式是指全局对象,即Window。
  2. 迭代面板但不将其分配给任何东西。
  3. 将节点存储在panels
  4. 将面板节点与传递给 showPanel 的节点进行比较

我更新了你的小提琴:http: //jsfiddle.net/bNzVA/2/

// 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++) {
        var p = panels[i]
        if (p === panel) {
            // Show panel
            // this referred to global object, i.e. window
            p.style.display = "block";
        } else {
            // Hide
            p.style.display = "none";
        }
    }
}

showPanel(homePanel);
于 2013-01-29T04:59:27.030 回答