如何根据元素是否包含特定的 class 构造 运行 函数的 switch 语句?
how to construct a switch statement to run a function depending on if an element contains a particular class?
如何将以下内容转换为 switch 语句?
if (event.target.classList.contains('ClassName')) {
callFunction1()
} else if (event.target.classList.contains('anotherClassName')) {
callFunction2()
}
有问题的 html 看起来像这样:
<div class="ClassOne classTwo className"></div>
<div class="ClassThree classFour anotherClassName"></div>
我知道这是不正确的,但它让我了解了我正在尝试做的事情。
switch (event.target) {
case "className":
function1(event.target)
break
case "anotherClassName":
function2(event.target)
break
}
你可以这样做:
switch (true) {
case event.target.includes('className'):
function1(event.target)
break
case event.target.includes('anotherClassName'):
function2(event.target)
break
}
但就我个人而言,我认为以这种方式使用 switch 语句是违反直觉的。在您的案例中使用 if
和 else if
有什么问题?
如何将以下内容转换为 switch 语句?
if (event.target.classList.contains('ClassName')) {
callFunction1()
} else if (event.target.classList.contains('anotherClassName')) {
callFunction2()
}
有问题的 html 看起来像这样:
<div class="ClassOne classTwo className"></div>
<div class="ClassThree classFour anotherClassName"></div>
我知道这是不正确的,但它让我了解了我正在尝试做的事情。
switch (event.target) {
case "className":
function1(event.target)
break
case "anotherClassName":
function2(event.target)
break
}
你可以这样做:
switch (true) {
case event.target.includes('className'):
function1(event.target)
break
case event.target.includes('anotherClassName'):
function2(event.target)
break
}
但就我个人而言,我认为以这种方式使用 switch 语句是违反直觉的。在您的案例中使用 if
和 else if
有什么问题?