简体   繁体   English

加+1 <input> 每个点击事件的价值。 增量停止在第3个Javascript / jQuery

[英]add + 1 to <input> value for each click event. increment stops at number 3 Javascript/jQuery

by default my input value is 1 , i want to add +1 each time i click my button . 默认情况下,我的输入值为1 ,我想每次单击button都加+1。 it stops adding when when it reaches 20 . 当它达到20时,它停止添加。

i cant figure out why my code stops at number 3 and just repeats 3 . 我不知道为什么我的代码停在3而只重复3

在此处输入图片说明

this is my HTML 这是我的HTML

<input type="hidden" id="total" value="20" /> //total num
<input type="hidden" id="cur_num" value="1" /> //current num
<button type="button" id="add" >Add</button>

this is javascript and demo here http://jsfiddle.net/zXpen/ 这是javascript和演示http://jsfiddle.net/zXpen/

$(document).ready(function() {
    $(document).on("click", "#add", function() {

        cur = $('#cur_num').val();
        total = $('#total').val();
        console.log(cur);

        if (cur <= total) {
            cur = parseInt(cur)+parseInt(1);
            $('#cur_num').val(cur);
        }
    });
});

You need to convert your values to integers: 您需要将值转换为整数:

cur = parseInt($('#cur_num').val());
total = parseInt($('#total').val());

At the moment your code is comparing "2" <= "20", then "3" <= "20" (as strings). 目前,您的代码正在比较“ 2” <=“ 20”,然后是“ 3” <=“ 20”(作为字符串)。 Therefore the if condition is not met and the code within it is not run. 因此,如果不满足if条件,并且其中的代码不会运行。

Also, you don't need parseInt(1) . 另外,您不需要parseInt(1) cur = parseInt(cur)+1; is fine. 很好

.val() returns a string, so cur <= total is comparing two strings lexicographically, ie characters at each position are compared against each other. .val()返回一个字符串,因此cur <= total在字典上比较两个字符串,即,将每个位置的字符相互比较。 And "2" in "20" is smaller than "3" in "3" . 并且"2"中的"20"小于"3"中的"3"

You have to convert the values to numbers before you compare them, not after that, eg by using the unary plus operator. 您必须先将值转换为数字,然后再进行比较,而不是之后,例如,使用一元加号运算符。 Also don't forget to declare your variables with var : 另外,不要忘记使用var声明变量:

var cur = +$('#cur_num').val();
var total = +$('#total').val();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM