2012-07-15 54 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 
} 
}