问题
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:
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();
}
Or using ternary operator
$('.WBE')[~str.indexOf('1') ? 'show' : 'hide']();
$('.VOBE')[~str.indexOf('2') ? 'show' : 'hide']();
$('.MBE')[~str.indexOf('3') ? 'show' : 'hide']();
Looping through array and ternary operator
['WBE', 'VOBE', 'MBE'].forEach(function(class, index) {
$(class)[~str.index(index+1) ? 'show' : 'hide']();
});
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...
回答2:
You can convert the string value to an array and check the values it contains using $.inArray
:
var values = $('#reg').val().split(',');
$('.WBE')[$.inArray('1', values) != -1 ? 'show' : 'hide']();
$('.VOBE')[$.inArray('2', values) != -1 ? 'show' : 'hide']();
$('.MBE')[$.inArray('3', values) != -1 ? 'show' : 'hide']();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="WBE">WBE</div>
<div class="VOBE">VOBE</div>
<div class="MBE">MBE</div>
<input id="reg" value="1,3" />
来源:https://stackoverflow.com/questions/30398651/how-to-compare-value-with-comma-separated-value-in-javascript-or-jquery