Store incremented value within a Jquery click function

Asked

Viewed 181 times

0

I have the following function.

 $('#proximo').click(function() {
         token = localStorage.getItem("userToken"); 

          page =0;

            var e = document.getElementById("idSelecionaSize");
            var size = e.options[e.selectedIndex].value;

            var search = $location.search();
            var page = search.page||page;
            var size = search.size||size;
            var sort = search.sort||'type,desc';

             page++;


            $http({
                 method: 'GET',
                 url: '/user/distritosPaginacao?page=' + page + '&size=' + size + '&sort=' + sort
            }).then(function(response) {
                $scope.distritos = response.data.content;
                $scope.number= response.data.number;
                $scope.page = response.data.totalPages;
                $scope.sort = sort;
                $scope.size= response.data.size;

            });

        });

When the user clicks on the button the page will receive the value 1 but in the second click the button will return to the value 1. I would like that, when clicking, the value is 2, 3, 4, ... and so on.

How to do ?

1 answer

2


You are assigning the value "0" to the variable "page", then you are redeclareting it (I imagine here is another variable) and at the end you are incrementing it by 1. To function, your variable needs to be declared in global scope, i.e., outside of this method. After declared and started with the value "0" outside this method, it will keep the last assigned value.

Ex.:

var pageIndex = 0;

$('#proximo').click(function() {
         token = localStorage.getItem("userToken"); 

            var e = document.getElementById("idSelecionaSize");
            var size = e.options[e.selectedIndex].value;

            var search = $location.search();
            var page = search.page||pageIndex;
            var size = search.size||size;
            var sort = search.sort||'type,desc';

             pageIndex++;


            $http({
                 method: 'GET',
                 url: '/user/distritosPaginacao?page=' + page + '&size=' + size + '&sort=' + sort
            }).then(function(response) {
                $scope.distritos = response.data.content;
                $scope.number= response.data.number;
                $scope.page = response.data.totalPages; // Sugiro trocar o nome desta variável para evitar ser confundida com a variável page acima
                $scope.sort = sort;
                $scope.size= response.data.size;

            });

        });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.