So I have a div that contains a number of other divs. Each of these other divs has a class called record. I only use this class to select all of these divs.
<div id = "resultContainer">
<div class="record">result1</div>
<div class="record">result2</div>
<div class="record">result3</div>
<div class="record">result4</div>
</div>
I also add a click event=
$(".record").click(function(e) {
do stuff here....
});
Now I want to dynamically add another div.
$("#resultContainer").append("<div class='record'>result5>/div>");
But now that click event is not added to the record.
My idea was to create a function called update()
that executed the $(".record....
code and call the function each time I added a record. But then the original divs do the action more than once!
How do I get all of my divs, regardless of when they were added, to before the do stuff here...
exactly once when clicked?
thanks!
In addition, I also have buttons on the dynamic div. So a solution that was able to handle something lik this: $(".save").button({ icons: { primary: 'ui-icon-disk' }, text: false });
would be preferable.
Don't use .live()
in this case. This is a perfect situation for jQuery's .delegate()
method, which is more efficient.
$("#resultContainer").delegate('.record','click',function() {
// do stuff here...
});
Only clicks inside the resultContainer
need to be processed to see if they match .record
, where .live()
will need to process every click on the page.
http://api.jquery.com/live/:
Attach a handler to the event for all elements which match the current selector, now and in the future.
$(".record").live("click", function(e) {
//do stuff here...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With