如何通过javascript中的另一个变量递增变量[重复]

时间:2022-08-27 17:42:57

This question already has an answer here:

这个问题在这里已有答案:

Full Code below

完整代码如下

I want to add a number from a variable to the incrimented variable, but they don't add. instead they get concatinated.

我想从变量中添加一个数字到incrimented变量,但是它们不会添加。相反,他们得到了连环。

This line

countScroll-=parseInt(scrollWidth_g);

if "scrollWidth_g" is 300 and "countScroll" is 10, i get 10300 and i want 310;

如果“scrollWidth_g”为300且“countScroll”为10,则得到10300,我想要310;

$(document).ready(function(e) {
    var countScroll = 10;
    $(document).on('click', '.scroller_g_nav', function(){
        var nav = $(this).attr('data-nav');
        var scrollWidth = $('.scroller_g').attr('data-scrollwidth');
        if (typeof scrollWidth == 'undefined'){
        var scrollWidth_g = 200;
        } else {
            var scrollWidth_g = scrollWidth;
            }

        if (nav == 'left'){         
                countScroll-=parseInt(scrollWidth_g);
                $('.scroller_g').animate({scrollLeft:countScroll},600);
            } else {
                countScroll+=scrollWidth_g;
                $('.scroller_g').animate({scrollLeft:countScroll},600);
        }
    });
});

1 个解决方案

#1


2  

You dont need to parse string number ("123") when you substract, but it is needed when you add the numbers.

在减法时,您不需要解析字符串编号(“123”),但在添加数字时需要它。

Example: "12" - 1 = 11
         "12" + 1 = 121 //here you need to parse string to number to get correct result 
         parseInt("12") + 1 = 11 


It works : 

    if (nav == 'left'){         
                countScroll -= parseInt(scrollWidth_g);
                $('.scroller_g').animate({scrollLeft:countScroll},600);
            } else {
                countScroll += parseInt(scrollWidth_g);
                $('.scroller_g').animate({scrollLeft:countScroll},600);
    }

#1


2  

You dont need to parse string number ("123") when you substract, but it is needed when you add the numbers.

在减法时,您不需要解析字符串编号(“123”),但在添加数字时需要它。

Example: "12" - 1 = 11
         "12" + 1 = 121 //here you need to parse string to number to get correct result 
         parseInt("12") + 1 = 11 


It works : 

    if (nav == 'left'){         
                countScroll -= parseInt(scrollWidth_g);
                $('.scroller_g').animate({scrollLeft:countScroll},600);
            } else {
                countScroll += parseInt(scrollWidth_g);
                $('.scroller_g').animate({scrollLeft:countScroll},600);
    }

相关文章