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>