如何在javascript或jquery中将值与逗号分隔值进行比较 [英] how to compare value with comma separated value in javascript or jquery

查看:25
本文介绍了如何在javascript或jquery中将值与逗号分隔值进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将值与 javascript 或 jquery 中的逗号分隔值进行比较.为此,我做了以下代码,还剩下什么?:

I wanted to compare value with comma separated value in javascript or jquery. for that i did following code, what is remaining?:

 var str = $('#reg').val();
 // i got str = 1,2,3

我需要将它与值进行比较,所以我该怎么做:

i need to compare it with values so how can i do this:

if (str == 1) {
    $('.WBE').show();
} else {
    $('.WBE').hide();
}

if (str == 2) {
    $('.VOBE').show();
} else {
    $('.VOBE').hide();
}

if (str == 3) {
    $('.MBE').show();
} else {
    $('.MBE').hide();
}

推荐答案

如果您正在尝试检查字符串是否包含 1,2 或 3,那么您可以这样做:

If you are trying to check if the string contains 1,2, or 3 then you can do like this:

var str = $('#reg').val();

if(str.indexOf("1") != -1) {
    $('.WBE').show();
} else {
    $('.WBE').hide();
}
if(str.indexOf("2") != -1) {
    $('.VOBE').show();
} else {
    $('.VOBE').hide();
}
if(str.indexOf("3") != -1) {
    $('.MBE').show();
} else {
    $('.MBE').hide();
}

或使用三元运算符

$('.WBE')[~str.indexOf('1') ? 'show' : 'hide']();
$('.VOBE')[~str.indexOf('2') ? 'show' : 'hide']();
$('.MBE')[~str.indexOf('3') ? 'show' : 'hide']();

遍历数组和三元运算符

['WBE', 'VOBE', 'MBE'].forEach(function(class, index) {
    $(class)[~str.index(index+1) ? 'show' : 'hide']();
});

这仅在您有 0-9 时才有效.如果您有 2 位或更多位数字,那么您可能应该转换为数组并检查数组是否包含数字...

This will only work if you have 0-9. If you have 2 or more digit numbers then you should probably convert to array and check if array contains the number...

这篇关于如何在javascript或jquery中将值与逗号分隔值进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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