2 Replies Latest reply on Mar 6, 2009 1:38 AM by am_doherty

    addEventListener variable bug?

    nox.freak
      When I try and pass a variable into a function under addEventListener it always returns the last variable.
      eg.
      for(var i=0;i<3;i++)
      {
      document.getElementById(i).addEventListener('click', function(){foo(i);}, false)
      }

      when I click on any of the items it returns 3 no 0 on the first item and 1 on the second, it always returns 3.
        • 1. Re: addEventListener variable bug?
          am_doherty
          I have the same problem iterating through arrays to create event links.

          The following HTML/JS code works fine in a browser, it creates anchors with onclick events, drops them into a div with id 'log'. When clicked they update a H1 with id 'h1str':

          function report(str) {
          var item = document.getElementById('h1str');
          item.innerHTML = 'report:' + str;
          }

          fruitArray = new Array('apple','pear', 'mango');
          for (i in fruitArray) {

          strVal = "'" + fruitArray + "'";
          a = document.createElement('a');
          a.setAttribute('id' ,fruitArray
          );
          a.setAttribute('onclick', 'report(' + strVal + ')');
          a.innerHTML = strVal;
          a.setAttribute('href', '#');
          log.appendChild(a);

          The roughly equivalent AIR code however always sets the final value to all three events:

          function report(str) {
          var item = document.getElementById('h1str');
          item.innerHTML = 'report:' + str;
          }
          for (i in fruitArray) {
          strVal = "'" + fruitArray + "'";
          a = document.createElement('a');
          a.setAttribute('id' ,fruitArray
          );
          a.innerHTML = strVal;
          a.setAttribute('href', '#');
          a.onmousedown = function() { aggra(fruitArray ) };
          log.appendChild(a);
          }


          Air always gives me mango, where a browser gives me the fruit of my choice!
          • 2. Re: addEventListener variable bug?
            am_doherty Level 1
            Solved it by putting the element creation, settings and appending parts into a separate function, thus:

            quote:


            for ( var i in fruitArray )
            {
            createLink(fruitArray ) ;
            }



            quote:


            function createLink(textVar) {
            a = document.createElement('a');
            a.setAttribute('id' ,textVar);
            a.innerHTML = textVar;
            a.setAttribute('href', '#');
            a.onmousedown = function() { aggra(textVar) };
            log.appendChild(a);
            }