0

I really don´t know what is happening to me..

The code is like:

for (var j=0; j<tours.length; j++){
    var name = tours[j].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    $tourButton.click(function() {
        alert(name);
    }
}

I´m trying to bind the click event for each button which displays the tours name, but is always displaying the last tour name whichever the button I'm clicking.

What am I doing wrong?

Thanks!

2
  • That is because the loop is complete when you click the button. Do you want to append new buttons to the document? Commented Feb 13, 2013 at 13:39
  • Yes I want that.. I will try the examples below.. Commented Feb 13, 2013 at 13:45

4 Answers 4

1

You need to wrap the click handler in a closure to 'close-over' the value of the variable name before the for-loop moves on.

This is because the handler isn't actually executed until you click on it, so otherwise it will simply use the current value of name at that time (whatever the last value in the loop was).

for (var j=0; j<tours.length; j++){
    var name = tours[j].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    (function(n) {
        $tourButton.click(function() {
            alert(n);
        });
    })(name)
}
Sign up to request clarification or add additional context in comments.

Comments

0

When the click is triggered j will have value tours.length. You can lock the loop value, as well as the rest of the variables through closures.

for (var j=0; j<tours.length; j++){
  (function(){ 
    var currentJValue = j;
    var name = tours[currentJValue].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    $tourButton.click(function() {
        alert(name);
    }
  })();
}

Comments

0

Try this...

$('.div.button-inside ').on('click',function() {
    alert($(this).text());
}

Comments

0

no need to call click event inside loop..append the dynamically created button and call it outside the loop and use on delegate event

try this

 $(document).on('click','div.button-inside',function() {
    alert($(this).text());
}

you can go through the link if you want to read more about on delegate events...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.