.each () in pure Javascript

4

In a forum platform there is a paging system, and I would like to do this pagination via Ajax, for this, I built the following function:

//<![CDATA[
var Pagination = (function(w, d) {
    var pagination = {

        init: function() {
            this.run();
        },

        run: function() {

            w.addEventListener('DOMContentLoaded', function() {
                var links = d.querySelectorAll('p.paging a[href^="/t"]');

                for (var i = 0; i < links.length; i++) {
                    links[i].addEventListener('click', function(event) {

                        event.preventDefault();

                        var link = this.getAttribute('href'),
                            xhr = new XMLHttpRequest();
                        xhr.onload = function() {
                            d.querySelector('.main').innerHTML = this.responseXML.querySelector('.main').innerHTML;
                        };
                        xhr.open('GET', link);
                        xhr.responseType = 'document';
                        xhr.send();
                    });
                }
            });

        }
    };

    pagination.init();

}(window, document));
//]]>

It works perfect until the first click. But if I click on more than one link the function does not work at all and the page loads normally.

I'm pretty sure that the error is in my loop for() , I have not found a better way to do the Ajax function for every time I click a link on that page.

If there is any better way, I am grateful to know.

@Edit:

The structure of my HTML is more or less as follows:

<div class="main">
    <p class="paging">
        <a href="/topic/1">1</a>
        <a href="/topic/2">2</a>
        <a href="/topic/3">3</a>
    </p>
    <div class="topic">
        <div class="content">Conteúdo aqui.</div>
    </div>
</div>
    
asked by anonymous 26.07.2014 / 22:16

1 answer

5

In this your code is replacing the menu each time you load the .main div. This causes event handlers to be lost.

I see two options:

change the selector in the ajax callback to change the right content. Replacing for:

d.querySelector('.topic').innerHTML = this.responseXML.querySelector('.topic').innerHTML;

and so change only the relevant content and do not break the event droppers placed by your pagination.run();

reseting event hadlers every time you load new content , since rewriting elements of the DOM causes them to lose the event handlers that they had grabbed. So in ajax callback you can use:

xhr.onload = function() {
    d.querySelector('.main').innerHTML = this.responseXML.querySelector('.main').innerHTML;
    pagination.init();  // ou pagination.run();
};
    
27.07.2014 / 00:11