Suppose I have the following HTML and js
<div>
<div class="testdiv" id="test1">test</div>
<div class="testdiv" id="test2">test</div>
</div>
function DynamicEvents() {
$('.testdiv').click (function () {
DoSomething();
});
}
function RedrawHTML() {
$('#test1').html('new HTML');
DynamicEvents();
}
Everytime I’m calling RedrawHTML, I’m also calling DynamicEvents to rebind test1. Suppose I’m calling RedrawHTML several times to update the div. My question is this: when I click on test2, does the function DoSomething() get executed once or get executed as many times as I’ve called RedrawHTML()?
In order to properly use
.onyou need to bind the event(s) to a parent element that is currently present in the DOM. So if i were you i would give the parent div an id and bind the event to that. Here’s an exampleFor your html
In the JS
If there’s no parent element guaranteed to be in the DOM the time the event is bound, then you could in the worst case bind to the
bodyordocumentbut i do not recommend this approach.If you’re not using jQuery 1.7, the equivalent delegate code would be
You only need to do this once, all click events triggered by
.testdivwill bubble up to the#containerandDoSomething()will be executed.