rzclfy
rzclfy

Reputation: 55

Adding click to dynamically generated divs Jquery

I'm creating a bunch of Divs based on the number items in an array that I recieve from an AJAX. All of the divs have a unique Id and I want to add a Click event to each of the generated Divs. I want the user to click on one of the generated divs which will then post some data. This is the code I use but it doesn't work.

c=data.length

            for(i=0;i<c;i++){

                $('#result').prepend('<div class="validation" id="lv_'+i+'">'+data[i]+'</div> ');
                $("#lv_"+i).live('click', function(data){
                .$post("setLocation", {lv: lv}, function(data){
                    alert(data);
                });
            });

        } 

Upvotes: 0

Views: 1193

Answers (2)

Adam Rackis
Adam Rackis

Reputation: 83376

To have a certain event handler fire on all divs that have the class validation, whether dynamically added or not, you'd ideally use on

$(document).on("click", ".validation", function() {} );

If you're using an older version of jQuery, here's how you would do it with live:

$(".validation").live("click", function() {} );

Or, better than live would be delegate

$(document).delegate(".validation", "click", function() {} );

The reason why delegate and on are preferable to live is because live will go through the existing dom, and attach the relevant handler to all discovered elements. delegate and on simply listen for events to bubble up, and fire the handler when the selector matches. As a result, delegate and on are more performant.

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

Try:

$("#lv_"+i).on("click", {lv: lv}, function(data))

Upvotes: 0

Related Questions