我有一个函数,我们在其中比较值。我使用了两个if
else
条件,由于某种原因,它不会转到第二个if
语句。在这种情况下,Val将是男性或女性。我们正在检查男性或女性的价值观。我们将gender_val视为男性或女性,但不会转到下一个if语句。
var select_male = '';
var select_female = '';
var gender_val ='';
if ($.isNumeric(val)){
gender_val='';
}
else{
gender_val = val.toLowerCase();
}
if (gender_val == 'male' || gender_val == 'm'){
select_male = 'active';
}
else if (gender_val == 'female' || gender_val == 'f'){
select_female = 'active';
}
这是我的代码..它不会进入if (gender_val == 'male' || gender_val == 'm')
语句。有人可以帮我弄这个吗。
答案 0 :(得分:1)
让我们考虑您逐行编码,考虑val = "19"
:
var select_male = '';
var select_female = '';
var gender_val ='';
这里没有什么不对的。但是我可能会使用某种布尔值而不是空字符串。
if ($.isNumeric(val)) // what is val? if it is a number then of course you will never enter later statements. But for our "19" this is a solid true.
gender_val='';
else
gender_val = val.toLowerCase();
// lets add here a logging for val you will tell us what you are really receiving in val
console.log(val);
让我们回到条件。此时gender_val
为''
。
// false || false is false
if (gender_val == 'male' || gender_val == 'm')
select_male = 'active'; // we are not entering here
// false || false is false
else if (gender_val == 'female' || gender_val == 'f')
select_female = 'active'; // we are not entering here neither
所以我们结束了你的片段。最终结果是:
select_male is ''
select_female is ''
gender_val is ''
如果val
在某种程度上:male
,Male
,m
,M
等......最终结果将是:
select_male is 'active'
select_female is ''
gender_val is val in lowercase
female
,F
等的镜面反射...
让我们测试一下:
function test(val) {
// This is your code, only copied and pasted...
var select_male = '';
var select_female = '';
var gender_val ='';
if ($.isNumeric(val)) {
gender_val='';
}
else{
gender_val = val.toLowerCase();
}
if (gender_val == 'male' || gender_val == 'm') {
select_male = 'active';
}
else if (gender_val == 'female' || gender_val == 'f') {
select_female = 'active';
}
console.log([select_male, select_female, gender_val]);
}
// Some test call
test("19"); // Does not work due to $.isNumeric...
test("MaLe"); // Works!
test("f"); // Works!
test("what?"); // Nothing in the gender, is not passing the ifs.
test(undefined); // ooops! Error here!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
如果由undefined
生成toLowerCase
输入,请注意错误。