sdgaw erzswer sdgaw erzswer - 1 year ago 50
jQuery Question

jQuery initiating many buttons

I've been trying to get my head around this probably very simple problem.

I have dynamically generated links, for example #l1, #l2.. and for each link I have a containing an image img. Divs have IDs corresponding to links, for example #li1, when clicked, should toggle div with id #di1 and so on.

I wrote a test, where I iterate through ID numbers and construct jquery button listeners. Something in the lines of:

a = [1,2,3,4]; // those are link and div IDs
for (k=0;k<3;k++){
$("#"+"li"+a[k]).click(function() {

But what this gives me are listeners on all links, which toggle only the last div!

So again: I have links within a tag, which when clicked, should toggle a DIFFERENT div with corresponding ID.

What am I doing wrong here?


Answer Source

By the time click is invoked, value of k is 3(because of k++), just use this context.

Make sure for-loop should have k < 4 condition to iterate 4(0, 1, 2, 3) elements.

var a = [1, 2, 3, 4];
for (k = 0; k < 4; k++) {
  $("#li" + a[k]).click(function() {
<script src=""></script>
<div id="li1">li1</div>
<div id="li2">li2</div>
<div id="li3">li3</div>
<div id="li4">li4</div>

Going with your approach:

Use closure, inner function remembers the environment in which it is created!

var a = [1, 2, 3, 4];
for (k = 0; k < 4; k++) {
  $("#di" + a[k]).click((function(k) {
    return function() {
      $("#li" + a[k]).toggle();
<script src=""></script>

<div id="di1">Div 1</div>
<div id="di2">Div 2</div>
<div id="di3">Div 3</div>
<div id="di4">Div 4</div>

<div id="li1">Links 1</div>
<div id="li2">Links 2</div>
<div id="li3">Links 3</div>
<div id="li4">Links 4</div>