1

I'm working on an assignment which asks me to create a script that somehow uses closures to alert the index of an element in an HTML collection. It also requires I use nested loops to iterate over parent elements and their children. I have nearly everything working, but I think I'm not fully understanding how I could use a closure here to meet the assignment requirements.

http://jsfiddle.net/mcasavant/99b8g2xz/

<div class="disableLinks">
  <a href="http://www.google.com">Link 1</a>
  <a href="http://www.google.com">Link 2</a>
</div>

<div class="disableLinks">
  <a href="http://www.google.com">Link 3</a>
  <a href="http://www.google.com">Link 4</a>
</div>

var disableLinks = document.getElementsByClassName('disableLinks');

for(var i = 0; i < disableLinks.length; i++){
    var links = disableLinks[i].getElementsByTagName('a');
    for(var j = 0; j < links.length; j++){
        links[j].addEventListener('click', function(e){
            alert('You clicked on link index ' + j + 'of div index ' + i);   
        }, false);
    }
}

Clicking on Link 3 would cause the alert box to say something like:

"You clicked on link index 0 of div index 1"

Marc Casavant
  • 297
  • 2
  • 11

0 Answers0