0

HTML:

<a id="link1" href="#">LINK1</a>
<div id="text1" style="display: none;">text1 div</div>

<a id="link2" href="#">LINK2</a>
<div id="text2" style="display: none;">text2 div</div>

<a id="link3" href="#">LINK3</a>
<div id="text3" style="display: none;">text3 div</div>

JS:

for (var i = 0; i <= 500; i++) {
  $('#link' + i).click(function() {
    $('#text' + i).toggle('fast');
    return false;
  });
}

but it's not working. Idea is to make each #link(number) showing appropriate #text(number) block. But at this momenty my phpstorm says "i" is mutable variable.... Thanks in advance

Bedir Yilmaz
  • 3,823
  • 5
  • 34
  • 54
Alexander Kim
  • 17,304
  • 23
  • 100
  • 157

3 Answers3

4

You have a closure issue here, to avoid it just pass i as data to the event handler.

for (var i = 0; i <= 500; i++) {
  $('#link' + i).click(i, function(e) {
    $('#text' + e.data).toggle('fast');
    return false;
  });
}
Community
  • 1
  • 1
Musa
  • 96,336
  • 17
  • 118
  • 137
1

I think you could do the following:

Add a class "targetLink" to every :

<a id="link1" class="targetLink" href="#">LINK1</a>

Replace the for loop targeting the class itself:

$("a.targetLink").toggle(function() {
    $(this).next("div").slideDown(350);
}, function() {
    $(this).next("div").slideUp(350);
});

Fiddle: http://jsfiddle.net/VinnyFonseca/yxpCA/

EDIT: Extra functionality for closing previously opened div when clicking on another item.

$("a.targetLink").toggle(function() {
    $(".open").slideUp(350);
    $(this).next("div").slideDown(350).addClass("open");
}, function() {
    $(this).next("div").slideUp(350).removeClass("open");
});
Vinny Fonseca
  • 450
  • 3
  • 10
0

First edit the href attribute attribute to make reference to the corresponding Dom element and some class to identify the anchors.

<a id="link1" href="#text1" class="some-class">LINK1</a>
<div id="text1" style="display: none;">text1 div</div>

<a id="link2" href="#tex2" class="some-class">LINK2</a>
<div id="text2" style="display: none;">text2 div</div>

<a id="link3" href="#tex2" class="some-class">LINK3</a>
<div id="text3" style="display: none;">text3 div</div>

Then modify the javascript

$('.some-class').click(function() {
    $( $(this).attr('href') ).toggle('fast');
});
jcamelis
  • 1,289
  • 1
  • 9
  • 10