Failed to add onclick handler for hyperlink tag inside listitem

Trying to add onclick handler to my tabs and can't seem to select the DOM correctly. 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}
    }
  }
}

      

+1


source to share


4 answers


Your closure seems to be wrong. Try

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

      



If that works, the question will be tricking jQuery closures, loops and events

+2


source


I agree with RoBorg and suggest you familiarize yourself with JavaScript scopes. This will explain a lot.



0


source


On the first line of your JS, you create var lis

but then iterate over to items

. Is this really what you want?

0


source


full 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);
    }
  }

      

}

0


source







All Articles