Javascript JS-开关盒内的功能评估
我有ID为的对象,如Javascript JS-开关盒内的功能评估,javascript,switch-statement,Javascript,Switch Statement,我有ID为的对象,如alternative1,alternative2等。我想以相同的方式设置所有这些对象的样式,因此我正在尝试: switch (feature.id) { case 'marker': ... break; case feature.id.includes('alternative'): case 'connectionMarker': ... //add styling
alternative1
,alternative2
等。我想以相同的方式设置所有这些对象的样式,因此我正在尝试:
switch (feature.id) {
case 'marker':
...
break;
case feature.id.includes('alternative'):
case 'connectionMarker':
... //add styling
break;
这似乎不起作用。我怎样才能做到这一点?您可以使用一个简单的技巧:
switch (feature.id) {
case 'marker':
...
break;
case (feature.id.includes('alternative') ? feature.id : !feature.id):
// your code here
break;
case 'connectionMarker':
...
break;
}
由于feature.id
始终是字符串值,!feature.id
将始终返回false。因此,如果feature.id
包含“可选”这一行:
case (feature.id.includes('alternative') ? feature.id : !feature.id):
变成:
case feature.id:
这将始终是这种情况(如feature.id==feature.id
)。否则,该行的计算结果为:
case 0:
解释器将跳过它。当布尔值与开关中的字符串不匹配时,将其与大小写一起使用是没有意义的。我认为你需要重新考虑你的方法。似乎使用开关是错误的。
swich
使用开关。这意味着您需要将true
作为开关
值并检查比较结果,或者采用另一种方法。该函数调用会产生布尔结果,因此就好像您编写了case true
或case false
。检查这个postdocument.querySelectorAll(“[id^=alternative]”)。forEach(function(){this.classList.add(“alter”);})代码>或只是css:[id^=alternative]{color:red}