切换声明不起作用可能会产生误解

时间:2015-11-29 14:56:44

标签: javascript switch-statement

这应该很容易,但也许我很困惑switch语句的工作方式。我有一个与列表项关联的数据属性。当您单击列表项时,我将数据属性编号传递给交换机,如果数据属性和交换机相等,则应该运行该函数。这不是它的工作方式吗?这里的数字应该匹配,但我每次都获得默认值。但是,如果我硬编码正确的数字,它的功能。为什么是这样?谢谢Stack,

HTML:

        <ul class="carousel_indicators">
        <li class = "anchor">First Step</li>
            <li class = " nav_li sub_li active" data-pointer-slide = "10" data-target="#option-carousel" data-slide-to="0">Slider</li>
            <li class = "nav_li sub_li" data-pointer-slide = "21" data-target="#option-carousel" data-slide-to="1">Social Hub</li>
        <li class = "nav_li" data-pointer-slide = "32" data-target="#option-carousel" data-slide-to="2">The Spirit</li>
        <li class = "nav_li" data-pointer-slide = "44" data-target="#option-carousel" data-slide-to="3">Elephant People</li>
        <li class = "nav_li" data-pointer-slide = "55" data-target="#option-carousel" data-slide-to="4">Elephant Room</li>
        <li class = "nav_li" data-pointer-slide = "65" data-target="#option-carousel" data-slide-to="5">Features</li>
        <li class = "nav_li" data-pointer-slide = "76" data-target="#option-carousel" data-slide-to="6">Spirit Award</li>
        <li class = "nav_li"><a href = "{{'auth/logout'}}">Logout</a></li>
        <div class = "red_pointer"></div>
      </ul>

使用Javascript:

    $('.nav_li').click(function(){
      var $listItem = $(this);
      var $point = $('.red_pointer');
      var $rePoint = $listItem.attr('data-pointer-slide');
        console.log($rePoint);
    switch ($rePoint) {
        case 10:
            $point.animate({
               top: '10%'
            },1000);
            break;
        case 21:
            $point.animate({
                top: '21%'
            }, 1000);
            break;
        case 32:
            $point.animate({
                top: '32%'
            }, 1000);
            break;
        case 44:
            $point.animate({
                top: '44%'
            }, 1000);
            break;
        case 55:
            $point.animate({
                top: '55%'
            }, 1000);
            break;
        case 65:
            $point.animate({
                top: '65%'
            }, 1000);
            break;
        case 76:
            $point.animate({
                top: '76%'
            }, 1000);
            break;
        default:
            console.log($rePoint);
    }
});

1 个答案:

答案 0 :(得分:1)

为什么switch ($rePoint))还有额外的括号 - 它应该是switch ($rePoint)

还尝试将变量与字符串进行比较而不是数字。