2012-09-18 51 views
1

我是JavaScript新手,但如果有人能告訴我我錯過了什麼,我將不勝感激。Javascript函數的意外結果

基本上,我試圖從兩個輸入測試大的值。這是我迄今爲止所做的:

$('#than_stock_submit').click(function() { 
    var pur_rate = $('#pur_rate input').val(), 
     sell_rate = $('#sell_rate input').val(), 
     msg_div = $('#sell_rate .msg'); 

    if(greater_than(sell_rate, pur_rate, msg_div)==false){return false} 
}); 

function greater_than(a, b, msg_div){ 
    msg_div.show().html(''); 
    if(a > b){ 
     msg_div.show().html('<p class="success">Sell Rate is good</p>'); 
     return true; 
    } else { 
     msg_div.show().html('<p class="error">Sell Rate should be increased</p>'); 
     return false; 
    } 
} 

我檢查了幾個值。當我測試的值小於1000,並且類似的值如b = 500和a = 5000或b = 100和a = 1000時,則其工作。其他值不起作用。

其他測試值是:

  1. A = 751,B = 750和結果=真
  2. A = 0751,B = 750和結果=假
  3. A = 551,B = 750和結果=假
  4. A = 1051,b = 750和結果=假
  5. A = 7500,b = 750和結果=真
  6. 一個= 6000,b = 600和結果=真

我也用控制檯檢查:console.log(a + b);

控制檯窗口的結果與1000750(當值類似於a = 1000 & b = 750)或0752750(當值類似於a = 0752 & b = 750)類似。

謝謝。

回答

0

下面是一個更強大的解決方案(你正在做的是字符串比較而不是數字比較)。

function greater_than(a,b) { 
    // first, convert both passed values to numbers 
    // (or at least try) 
    var nA = new Number(a), 
     nB = new Number(b); 

    // check if they were converted successfully. 
    // isNaN = is Not a Number (invalid input) 
    if (!isNan(nA) && !isNaN(nB)) { 
    // now go ahead and perform the check 
    msg_div.empty().show(); 
    if (nA > nB) { 
     $('<p>',{'class':'success'}) 
     .text('Sell Rate is good') 
     .appendTo(msg_div); 
     return true; 
    } else { 
     $('<p>',{'class':'error'}) 
     .text('Sell Rate should be increased') 
     .appendTo(msg_div); 
    } 
    } 
    // In case you wanted to handle showing an error for 
    // invalid input, you can uncomment the following lines 
    // and take the necessary action(s) 
    else{ 
    /* one of them was not a number */ 
    } 
    return false; 
} 

請注意,我使用jQuery來構建您添加的<p>。我也用.empty()代替.html('')

和一些文檔:

+0

太棒了!非常感謝你。 您能告訴我爲什麼您使用 $('

',{'class':'success'}) .text('Sell Rate is good') .appendTo(msg_div); 而不是 msg_div.show()。html('

銷售率很好

'); and .empty()而不是指定.html('') – itskawsar

+0

使用提供的方法構建DOM比提供顯式HTML更安全。 –

0

您正在比較字符串,並且"1000">"99"爲false。

的解決方案是使用parseIntparseFloat第一解析你的號碼:

var pur_rate = parseFloat($('#pur_rate input').val()); 

var pur_rate = parseInt($('#pur_rate input').val(), 10); 
3

你應該比較(他們使用.val()時成爲字符串)前的字符串轉換爲數字。使用parseIntparseFloat

function greater_than(a, b, msg_div){ 
    a = parseInt(a, 10); 
    b = parseInt(b, 10); 
    // etc 
+2

並鏈接到['parseFloat'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseFloat)或['parseInt'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt)(整個數字爲'parseInt',數字可以包含十進制數字的'parseFloat') –

+0

已解決。非常感謝David和Chistie。 – itskawsar

+0

但你能告訴我,10是什麼? – itskawsar

0

讀取輸入值返回字符串。所以如果你比較字符串和字符串,這是一個ASCII比較,而不是數字。請使用parseInt(value, 10);永遠不要忘記基數! ;)