0

I have a list of links that will switch a display section of a div (like a carousel) and each link has an attribute for the slide.

In JavaScript the variable _pagerList is the list of objects, and each one will move the div to its corresponding slide. The problem is that all of them do the same, so I changed to an alert to see the 'data-slide' value and all of the return 6.

CODE

<!doctype html>

<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Document</title>
</head>
<body>
  <ul>
    <li><a class="pager-list" href="" data-slide="1"><img src="http://placehold.it/30" alt="" /></a></li>
    <li><a class="pager-list" href="" data-slide="2"><img src="http://placehold.it/30" alt="" /></a></li>
    <li><a class="pager-list" href="" data-slide="3"><img src="http://placehold.it/30" alt="" /></a></li>
    <li><a class="pager-list" href="" data-slide="4"><img src="http://placehold.it/30" alt="" /></a></li>
    <li><a class="pager-list" href="" data-slide="5"><img src="http://placehold.it/30" alt="" /></a></li>
    <li><a class="pager-list" href="" data-slide="6"><img src="http://placehold.it/30" alt="" /></a></li>
  </ul>

  <script>
    window.onload = function() {
      var _pagerList = document.querySelectorAll('.pager-list');

      for ( var i = 0; i < _pagerList.length; i++ ) {
        var p = _pagerList[i];

        p.onclick = function() {
          alert(p.getAttribute('data-slide')); 

          return false;
        };
      }
    }
  </script>
</body>
</html>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • 1
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Bergi Aug 05 '13 at 17:33

2 Answers2

2

You should change this line

alert(p.getAttribute('data-slide'));

to this

alert(this.getAttribute('data-slide')); 
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
1

for loops do not create a new context, so the var p statement will always leave p to be the last value set. To fix this, you'll want to use a closure.

Something like the following should work:

  for ( var i = 0; i < _pagerList.length; i++ ) {
    (function (p) {

        p.onclick = function() {
          alert(p.getAttribute('data-slide')); 

          return false;
        };
    })(_pagerList[i]);
  }

For more information about closures check this other SO question

Community
  • 1
  • 1
LoveAndCoding
  • 7,857
  • 2
  • 31
  • 55