So I wrote the code below:
jQuery('#contentWrapper').delegate(".addButton", "click", function(){
addRow(jQuery(this));
});
function addRow(thisButton){
var parent = thisButton.parent();
console.log("parent = ",parent);
var childrenNoEvents = thisButton.parent().children().clone(false);
console.log("childrenClone = ",childrenNoEvents);
var cloneWithoutEvents = thisButton.parent().clone(false);
console.log("parentClone = ",cloneWithoutEvents);
thisButton.parent().append(childrenNoEvents);
};
which operates on an DOM element like this
<div class="whatever">
<span>first element</span><span class="addButton">O</span><span class="deleteButton">X</span>
</div>
When I click the O(the DOM element with the addButton class) the first time it works properly, but subsequent times it creates/clones twice as many elements as the prior click. I assume it has to do with the delegate handler calling addRow for as many “.addButton” classes there are in the DOM but I don’t know how to fix it.
Bonus Question:
How would I use a closure to create a persistent variable that I can increment inside the addRow function each time the event is fired? (or is there a better way to do that?)
Everytime you execute the function, you copy the contents of .whatever back into .whatever, effectively doubling them. Try using this approach:
With HTML syntax like this:
You can test it with this JSFiddle: http://jsfiddle.net/ZsCCs/
More info about the .on() method: http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html