为什么这些div没有被隐藏和揭示

  • 本文关键字:隐藏 div javascript
  • 更新时间 :
  • 英文 :


我不知道为什么下面的代码会取消隐藏目标元素,但不会隐藏它们。 列表消息是从网络套接字接收的。 它的形式是:

"Line, 4, Auto"
"Line, 4, Heat"
"Line, 4, Cool"
"Line, 4, Fan"
"Line, 4, Off"

将列表推送到数组矩阵后,我使用开关块进入数组 [2] 的开关块。 代码会在适当的时候正确取消隐藏元素,但不会隐藏它们。

// dummy code
var lines = `Line 4, Heat;Line, 4, Cool;Line, 4, Auto;Line, 4, Fan;Line, 4, Off`.split(";");
lines.forEach(function(msg) {HideUnhide(msg) })
function HideUnhide(msg) {
// end dummy code
  var array = msg.split(',');
  alert(msg)
  switch (array[0]) {
    case "Line":
      switch (Number(array[1])) {
        case 0:
          document.getElementById("Scale").innerHTML = array[2];
          break;
        case 4:
          document.getElementById("Control").innerHTML = array[2];
          test = array[2];
          switch (test.trim()) {
            case "Auto":
                document.getElementById("Hot").style.visibility = "visible";
                document.getElementById("Cold").style.visibility = "visible";
                break;
            case "Heat":
                document.getElementById("Hot").style.visibility = "visible";
                document.getElementById("Cold").style.visibility = "invisible";
                break;
            case "Cool":
                document.getElementById("Hot").style.visibility = "invisible";
                document.getElementById("Cold").style.visibility = "visible";
                break;
              default:
                document.getElementById("Hot").style.visibility = "invisible";
                document.getElementById("Cold").style.visibility = "invisible";
                break;
          }
      }
  }
}
div.Hot {
  position: fixed;
  top: 75px;
  left: 24px;
  width: 100px;
  font: 20px Arial Bold;
  color: rgb(200, 200, 200);
}
div.Cold {
  position: fixed;
  top: 50px;
  left: 24px;
  width: 100px;
  font: 20px Arial Bold;
  color: rgb(200, 200, 200);
}
div.Control {
        position: fixed;
        top: 25px;
        left: 24px;
        width: 100px;
        font: 20px Arial Bold;
        color: rgb(200,200,200);
}
div.Scale {
        position: fixed;
        top: 0px;
        left: 24px;
        width: 100px;
        font: 20px Arial Bold;
        padding-right: 30px;
        color: rgb(200,200,200);
}
<div id="Hot" style="visibility: hidden; color:rgb(200,200,200)" class="Hot">Cool: 70.0</div>
<div id="Cold" style="visibility: hidden; color:rgb(200,200,200)" class="Cold">Heat: 64.0</div>
<div ID="Scale" style="color:rgb(200,200,200)" class="Scale">&#8457;</div>
<div ID="Control" style="color:black" class="Control">Cool</div>

您传递的数组元素是" Auto",您的switch语句在其中查找"Auto",请注意空格。您可以更改在源站创建消息的方式,也可以检查空格并将其删除,或者编辑 switch 语句以适应它。如果这是一种选择并且不会在其他地方创建更多工作,我建议在创建消息时删除空间。

我发现了问题。 语法为:

document.getElementById("Hot").style.visibility = "hidden";

不:

document.getElementById("Hot").style.visibility = "invisible";

最新更新