3

我遇到了这个问题。它使用 parseFloat 或 parseInt 添加数字。如果 textbox1 值为 4 并且 textbox2 值为 2 然后我得到输出(见脚本)

我的疑问是为什么另外单独

parseFloat($('#txt1').val()) + parseFloat($('#txt2').val())

给出正确的值但

parseFloat($('#txt1').val() + $('#txt2').val())

没有给出正确的值,而

  • parseFloat($('#txt1').val() - $('#txt2').val()),
  • parseFloat($('#txt1').val() / $('#txt2').val()),
  • parseFloat($('#txt1').val() * $('#txt2').val())

给出正确的值。它很简单,但我找不到解决方案。

=====jQuery

   function Calculate() {                                              //--> Output
     $('#lbl1').html(parseFloat($('#txt1').val() + $('#txt2').val())); //--> 42
     $('#lbl2').html(parseFloat($('#txt1').val()) + parseFloat($('#txt2').val())); //--> 6
     $('#lbl3').html(parseFloat(4 + 2));                               //--> 6

     $('#lbl4').html(parseFloat($('#txt1').val() - $('#txt2').val())); //--> 2
     $('#lbl5').html(parseFloat($('#txt1').val() * $('#txt2').val())); //--> 8
     $('#lbl6').html(parseFloat($('#txt1').val() / $('#txt2').val())); //--> 2
  }

=====HTML

<table>
        <tr>
            <td>
                <input type="text" id="txt1" />
            </td>
            <td>
                <input type="text" id="txt2" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="Calculate"  onclick="Calculate()" />
            </td>
            <td>
                <label id="lbl1">
                </label>
                |
                <label id="lbl2">
                </label>
                |
                <label id="lbl3">
                </label>
                |
                <label id="lbl4">
                </label>
                |
                <label id="lbl5">
                </label>
                |
                <label id="lbl6">
                </label>
            </td>
        </tr>
    </table>
4

2 回答 2

10

$.val() returns a string value.

So in your first example you convert both returned strings to numbers and the calculation is fine.

If you use parseFloat($('#txt1').val() + $('#txt2').val()) the + does not work as the arithmetic operator, but as a string concatenation. So you concatenate both strings and convert them afterwards, which gives a wrong result.

The examples using - will work, as there is no string operation using - and by thus alls values get implicitly converted to a number before the operation is applied.

于 2013-04-20T07:47:33.833 回答
1

$('#txt1').val() + $('#txt2').val() it gives String value

you can not use - , * , /operator on strings

parseFloat($('#txt1').val()), parseFloat($('#txt2').val()) returns numbers not strings

于 2013-04-20T07:45:42.510 回答