如果那么其他的jquery

时间:2013-12-28 20:14:27

标签: jquery if-statement conditional-statements

所以我让这段代码运行良好

 <script type="text/javascript">
    document.onkeyup = KeyCheck;       
    function KeyCheck(e)
            {
        var KeyID = (window.event) ? event.keyCode : e.keyCode;
            switch(KeyID)   {
        case 37:
                window.location = "<?php echo get_permalink(get_adjacent_post(false,'',false)); ?>";
                break;
        case 39:
                window.location = "<?php echo get_permalink(get_adjacent_post(false,'',true)); ?>";
                    break;
             }}

然后我尝试添加'if then else'条件

   <script type="text/javascript">
        document.onkeyup = KeyCheck;           
        function KeyCheck(e)
            {
           if(window.location.href.indexOf("?category") > -1) {
                  var KeyID = (window.event) ? event.keyCode : e.keyCode;
                switch(KeyID)   {
                case 37:
                window.location = "<?php echo get_permalink(get_adjacent_post(true,'',false)); ?>?category";
                break;
                case 39:
                window.location = "<?php echo get_permalink(get_adjacent_post(true,'',true)); ?>?category";
                    break;
                    }  
           else { var KeyID = (window.event) ? event.keyCode : e.keyCode;
                switch(KeyID)   {
                case 37:
                window.location = "<?php echo get_permalink(get_adjacent_post(false,'',false)); ?>";
                break;
                case 39:
                window.location = "<?php echo get_permalink(get_adjacent_post(false,'',true)); ?>";
                    break;} 
             }}
     </script>

现在它根本不起作用?代码看起来很丑陋,我确信有更清洁的方法。但我不明白为什么它现在不起作用?

1 个答案:

答案 0 :(得分:1)

如果代码在第一个示例中有效,那么第二个示例中必定会出现错误。

您不需要if/else。您可以将其重写为:

document.onkeyup = keyCheck;   

function keyCheck(e)
{
    var keyID = e.which;
    var isCategory = window.location.href.indexOf("?category") > -1;

    switch(keyID)   {
        case 37:
        case 39:
            window.location = "<?php echo get_permalink(get_adjacent_post(isCategory, '', true)); ?>";
            break;
    }
}