0

I currently have code that does this:

$('#BoxShadow_1').click(function()
{
addDivBoxShadow('BoxShadow_1');
});

$('#BoxShadow_2').click(function()
{
addDivBoxShadow('BoxShadow_2');
});

...etc for 10 similar elements. It works just fine.

I am using JQuery also.

I want to change the code to something like this:

for (i = 1; i < 11; i++) {

    $('#BoxShadow_' + i).click(function(){
      addDivBoxShadow("BoxShadow_" + i);
    });

}

Challenge is this:

BoxShadow_10 is assigned to all of the divs rather than BoxShadow_1, BoxShadow_2 etc.

FYI the code I am trying to effect is a math game I wrote at this URL:

tinyurl.com/sashamath

Thanks in advance. And I hope to contribute in the future.

Ok, so here is the answer, using the 'let' statement as follows:

for (let i = 1; i < 11; i++) {

    $('#BoxShadow_' + i).click(function(){
      addDivBoxShadow("BoxShadow_" + i);
    });

}

1 Answers1

2

The trouble with your loop is the classic "callback in a loop" problem. '

However you don't need a loop at all. Just use the id property of this to get the ID.

function handler() {
  addDivBoxShadow(this.id);
}

$('#BoxShadow_1').click(handler);
$('#BoxShadow_2').click(handler);

Or if you change the addDivBoxShadow function to use this to get the element, you can pass it directly.

$('#BoxShadow_1').click(addDivBoxShadow);
$('#BoxShadow_2').click(addDivBoxShadow);

So now addDivBoxShadow can use this to reference the bound element, and it will also receive the event object as an argument.


And of course it can be done with a single selector too.

$('#BoxShadow_1, #BoxShadow_2').click(addDivBoxShadow);
llama
  • 2,535
  • 12
  • 11