jQuery IF具有多个值的show和hide元素 [英] JQuery IF with multiple value show and hide element

查看:105
本文介绍了jQuery IF具有多个值的show和hide元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jquery还是很陌生,请为我的以下问题提供任何帮助:

I'm quite new with jquery, kindly need any of your assitance for my below question:

我有一个输入,用户可以输入小于3位数字的 数字 ,并以 前缀以某些"数字开头 ,如果满足条件,则会显示特定的元素,否则将被隐藏.

I have an input where users can type some number that less than 3 digit, and have prefix start with "certain" number, if condition is met, a specific element will be displayed, otherwise it will be hidden.

我的问题是,如果我有10个或更多的这种情况,我的代码将会很长,并且明显会降低性能. 有没有简单的方法可以做到这一点?

My problem is, if I have 10 or more of this condition, my code will be so long, and obviously decrease the performance. Is there any simple way to achieve this ?

$(function(c) {

    $('#check').on('keyup change', function(c) {
    var one = $('#check');
    if( (one.val() == 123) || (one.val() == 124) ) {
            $('#one').show();
        } else if (this.value.length < 3 ) {
            $('#one').hide();
        }
    }); 
    
    $('#check').on('keyup change', function(c) {
    var two = $('#check');
    if( (two.val() == 234) || (two.val() == 235) ) {
            $('#two').show();
        } else if (this.value.length < 3 ) {
            $('#two').hide();
        }
    });
    
        $('#check').on('keyup change', function(c) {
    var three = $('#check');
    if( (three.val() == 345) || (three.val() == 346) ) {
            $('#three').show();
        } else if (this.value.length < 3 ) {
            $('#three').hide();
        }
    });
});

#one {
display: none;
}
#two {
display: none;
}
#three {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<input type="text" id="check" maxlength="10">

<div id="one">
<br>
ONE
</div>

<div id="two">
<br>
TWO
</div>

<div id="three">
<br>
THREE
</div>

提前谢谢!

推荐答案

尝试一下:

$('#check').on('keyup change', function(c) {

    //initially hide all
    if(this.value.length < 3){
        $('#three, #two, #one').hide();
    }
    else{

        switch(parseInt(this.value)){

            case 123: case 124: $('#one').show(); break;
            case 234: case 235: $('#two').show(); break;
            case 345: case 346: $('#three').show(); break;
        }

    }
});

这篇关于jQuery IF具有多个值的show和hide元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆