【发布时间】:2019-07-10 14:46:07
【问题描述】:
我不明白为什么下面的代码会取消隐藏目标元素,但不会隐藏它们。列表 msg 是从 websocket 接收的。它的形式是:
"Line, 4, Auto"
"Line, 4, Heat"
"Line, 4, Cool"
"Line, 4, Fan"
"Line, 4, Off"
将列表推入数组矩阵后,我使用开关块进入array[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">℉</div>
<div ID="Control" style="color:black" class="Control">Cool</div>
【问题讨论】:
-
array[2]中可能有前导或尾随空格吗?您可以使用类似strip的方法来删除它。 -
我认为你必须修剪空白。在第一种情况下,您会通过 Number() 调用对其进行修剪,但在第二种情况下,您会尝试将“Auto”与“Auto”匹配。
-
您的代码也不完整。请单击
[<>]sn-p 编辑器并生成minimal reproducible example,例如使用var lines = `Line, 4, Auto Line, 4, Heat Line, 4, Cool Line, 4, Fan Line, 4, Off`.split(/\n/); lines.forEach(msg => { .... }) -
在这种情况下,您不需要大括号围绕 switch 语句案例。请参阅 this 了解何时使用它们以及它们的用途。
-
我已修改您的问题,将代码包含为可运行的 sn-p。请修复您的语法错误(如果它们没有价值,则将其注释掉),以便我们可以复制您描述的问题。 (您的“占位符”
forEach,以及无效的switch语法 - 不应该有:)
标签: javascript