sdgaw erzswer
sdgaw erzswer

Reputation: 2382

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() {
        $("#"+"di"+a[k]).toggle();
    });
}

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?

Thanks..

Upvotes: 1

Views: 33

Answers (2)

RyanNerd
RyanNerd

Reputation: 3189

You can also use forEach() as well for cleaner JS code (IMO):

// link and div IDs
var a = [1,2,3,4];
a.forEach(function (v)
{
	$("#li" + v).click(function()
	{
		$("#di" + v).toggle();
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
	<li id="li1">one</li>
	<li id="li2">two</li>
	<li id="li3">three</li>
	<li id="li4">four</li>
</ul>

<div id="di1">
	<p>One</p>
</div>
<div id="di2">
	<p>Two</p>
</div>
<div id="di3">
	<p>Three</p>
</div>
<div id="di4">
	<p>Four</p>
</div>

Upvotes: 1

Rayon
Rayon

Reputation: 36609

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() {
    $(this).toggle();
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></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();
    }
  })(k));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></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>
<hr>
<hr>

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

Upvotes: 1

Related Questions