【问题标题】:how to construct a switch statement to run a function depending on if an element contains a particular class?如何根据元素是否包含特定类来构造 switch 语句来运行函数?
【发布时间】:2021-09-15 19:36:28
【问题描述】:

如何将以下内容转换为 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
}

【问题讨论】:

    标签: javascript switch-statement conditional-statements


    【解决方案1】:

    你可以这样做:

    switch (true) {
        case event.target.includes('className'):
            function1(event.target)
            break
        case event.target.includes('anotherClassName'):
            function2(event.target)
            break
    }
    

    但就个人而言,我认为以这种方式使用 switch 语句是违反直觉的。在您的情况下使用 ifelse if 有什么问题?

    【讨论】:

    • 会有很多条件,通常 switch 语句在这些情况下更具可读性。
    猜你喜欢
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2015-09-17
    • 2023-03-03
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多