views:

656

answers:

4

Trying to add an onclick handler to my tabs, and can't seem to get the DOM selection right. Can you guys help?

  <div id="tabstrip">
    <ul>
      <li id="a" class="selected"><a href="#">A</a></li>
      <li id="b"><a href="#">B</a></li>
      <li id="b"><a href="#">C</a></li>
    </ul>
  </div>

function initTabStrip()
{
  var lis = document.getElementById('tabstrip').getElementsByTagName('li');
  for (var i=0;i<items.length;i++)
  {
    var as = items[i].getElementsByTagName('a');
    for (var j=0;j<as.length;j++)
    {
      as[j].onclick=function(){changeTab(items[i].id);return false}
    }
  }
}
+2  A: 

Seems like your closure is wrong. Try

as[j].onclick = function(items, i)
{
    return function()
    {
        changeTab(items[i].id);
        return false;
    };
}(items, i);

If it works then the question is a dupe of http://stackoverflow.com/questions/359467/jquery-closures-loops-and-events#359505

Greg
A: 

I agree to RoBorg and suggest reading about JavaScript scopes. It will explain a lot.

Vilx-
A: 

First line of your JS, you create var lis but then you iterate on items. Is that really what you want ?

Guillaume
A: 

complete function, with changes suggested by RoBerg:

function initTabStrip()
{
  var tabstrip = document.getElementById('tabstrip');
  var items = tabstrip.getElementsByTagName('li');
  for (var i=0;i<items.length;i++)
  {
    var as = items[i].getElementsByTagName('a');
    for (var j=0;j<as.length;j++)
    {
      as[j].onclick = function(items, i)
      {
        return function()
        {
          changeTab(items[i].id);
          return false;
        };
      }(items, i);
    }
  }

}

Cliff