I have the following HTML:
<div id="Content">
<div class="MyDiv">...</div>
<div class="MyDiv">...</div>
</div>
The MyDiv elements are removed and added several times as the result of an ajax call. I use the a function that uses the .html() function to replace the HTML.
When the page loads, I execute the following function:
function DynamicHandlers() {
$('#Content .MyDiv').live({
click: function () { .... },
mouseleave: function () { ... }
});
The problem is that the click and mouseleave handlers are executed as many time as I’ve changed the HTML. I initially had the handlers tied to the creation of the HTML and I’d bind the events each time the HTML was updated. I thought that by moving the handlers to the function that uses the .live(), I only had to run it once and then the handlers would be set for good. Which they are; the only problem is that they get executed multiple times.
What are the changes I need to make?
Thanks.
Your handler will be invoked for each element in the DOM that matches the $(‘#Content .MyDiv’) selector. I assume that at the time the event is fired there are multiple elements on the page that match.