0

First of all, sorry for bad english.

So what I've to do is a simple web page with only 2 links, and when you click one button, it loads (in the same page) the content of a concrete .html file.

For example: link 1 (with id "L1") shows the content of L_1.html, meanwhile the link 2 (with id "L2") shows the content of L2.html.

The problem in my code is that, no matter which button I press, it always loads the second .html file. I leave all my code here:

Index.html -->

<body>
<div id="losEnlaces">
<a href="#" id="e1">Link 1</a>
<a href="#" id="e2">Link 2</a> 
</div>

<div id="show">
    Here will be the future content
</div>

The other 2 .html files only has an <h1>page number X</h1> each one. (their names are E2_1.html and E2_2.html)

.js file -->

 window.onload=function(){
    var enlaces=document.getElementsByTagName("a");
    var pag;
    var laID;
    for (var i = 1; i <= enlaces.length; i++) {
        pag="E2_"+i+".html";
        laID="e"+i;
        document.getElementById((laID)).addEventListener("click",function(){
            mostrarHTML(pag,'show');
        },false);
    };
 }

 function mostrarHTML(data, idDiv){
    var XMLHttpRequestObject = false;
    if (window.XMLHttpRequest) {
        XMLHttpRequestObject = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if(XMLHttpRequestObject) {
        var objeto = document.getElementById(idDiv);
        XMLHttpRequestObject.open("GET", data);
        XMLHttpRequestObject.onreadystatechange = function(){
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                objeto.innerHTML = XMLHttpRequestObject.responseText;
        }
    }
    XMLHttpRequestObject.send(null);
 }
 }
Alex
  • 750
  • 5
  • 15
  • 33
  • 2
    Your problem are how scopes and closures work in js, the `pag` will always be the same due to this. Check this question and the answer to it: [JavaScript for loop index strangeness](http://stackoverflow.com/q/2803351/1960455) – t.niese Jan 13 '14 at 00:21

1 Answers1

0

I've finally solved it by changing the addeventlistener to this:

document.getElementById(laID).addEventListener("click",(function(pag){
            return function(){
                mostrarHTML(pag,'mostrador');
            }
        })(pag),false);
Alex
  • 750
  • 5
  • 15
  • 33