2012-07-15 55 views
0

我在处理json请求中的一些数字时遇到问题。基于结果我试图输出一些HTML的各种位。具体问题是,当我来检查一个数是否大于-1,但小于6.代码摘录如下...jQuery中条件语句的问题

else if(parseInt(myvariable, 10) < -1) { 
//this is where one thing happens 
} 
else if(parseInt(myvariable, 10) > -1) { 
//Something else happens here 
} 
else if(parseInt(myvariable, 10) > 6) { 
//This is where the third thing should happen, but doesn't? 
} 

看来,尽管值是7或70,第二“其他如果'尽可能多。

有没有一种方法可以检查数字是否大于-1但小于6,以便它移动到下一个条件语句。

我在猜测(就像我以前的问题)有一个非常简单的答案,所以请原谅我的天真。

在此先感谢。

回答

0

条件直到一个被发现是正确的。

换句话说,您需要重新调整其订单或收紧它们以使您的当前订单生效。

7高于-1,所以第二个条件解析为true。所以7,第三个条件是不需要的。

if(parseInt(myvariable, 10) < -1) { 
    //number is less than -1 
} 
else if(parseInt(myvariable, 10) > 6) { 
    //number is above 6 
} 
else { 
    //neither, so must be inbetween -1 an 6 
} 
+0

- 谢谢你!惊人的快速答案。 – 2012-07-15 10:37:59

0

if条件错误。让我们想到这一点:MYVARIABLE是7

在你的代码将出现:

else if(parseInt(myvariable, 10) < -1) { 
//this is where one thing happens 
} 
else if(parseInt(myvariable, 10) > -1) { 
**// HERE THE CONDITION IS TRUE, BECAUSE 7 > -1** 
} 
else if(parseInt(myvariable, 10) > 6) { 
// This is where the third thing should happen, but doesn't? 
} 

你可以改变它作为

else if(parseInt(myvariable, 10) < -1) { 
//this is where one thing happens 
} 
else if(parseInt(myvariable, 10) > 6) { 
// This is where the third thing should happen, but doesn't? 
} 
else if(parseInt(myvariable, 10) > -1) { 
// Moved 
} 

为了使它工作...

0

是因为任何数量的你会写大于-1永远不会丢的第三个代码块,它会抛出第二,正如你所说的“数量超过-1但小于6“你可以简单地这样做:

else if(parseInt(myvariable, 10) < -1) { 
//this is where one thing happens 
} 
else if(parseInt(myvariable, 10) > -1 && parseInt(myvariable, 10) < 6) { 
//Something else happens here 
} 
+0

This works too,thanks @ Mohamed-Farrag – 2012-07-15 10:42:27

0

另一种解决方案是改变下联:

else if(parseInt(myvariable, 10) > -1) 

到:

else if(parseInt(myvariable, 10) <= 6) 

有很多写这种方法。

0

我想你可以做到这一点很容易做这样的事情:

考虑您的变量值(7):

else if(parseInt(myVariable, 10) &lt; -1) { 
//this is where one thing happens 
} 
else if(parseInt(myVariable, 10) > -1) { 
//now 'myVariable' is greater than -1, then let's check if it is greater than 6 
if(parseInt(myVariable, 10) > 6) { 
//this where what you should do if 'myVariable' greater than -1 AND greater than 6 
} 
}