vendredi 10 juin 2016

Pagination with jquery's click events


What I'm trying to do is I have a list of paginated elements, and I have a function that I want to call every time I click on a page. Here's my current code

function get_alerts(page){
    console.log('calling get_alerts');
    $.getJSON('/api/import_preview?p=1', function(data){
        $('#alerts').empty();
        $.each(data, function(key, val){
            $('#alerts').append(key);

        });
        populate_pagination(page, data['num_pages'])
    });
};

function populate_pagination(current_page, total_pages){
    var i;
    var page_element;
    $('.pagination').empty();
    for (i=current_page-5; i<current_page+5; i++)
    {
        console.log('i='+i)
        console.log('current_page='+current_page)
        if (i>0 && i<=total_pages){
            console.log('creating new element');
            page_element = $('<li><a href="#!">'+i+'</a></li>')
            page_element.addClass('waves-effect');
            //page_element.attr('onclick', 'get_alerts('+i+');');
            if (i==current_page){
                page_element.addClass('active');
            }
            else{
                page_element.click(function(event){get_alerts($(this).text());});
            }
            $('.pagination').append(page_element);
        };
    };
};

If I use the onclick approach, everything works great. But if I go with the click approach, something very odd happens, when I click on page 5, instead of adding pages from 1-10, it actually adds pages from 1-54. Then I wondered, I know it's not calling get_alerts multiple times. And I verified that current_page+5 is a static number, i on the other hand continues to go up even with the conditional i


Aucun commentaire:

Enregistrer un commentaire