I have the following code that is executed on the callback of an Ajax call:
jQuery.each(res, function ()
{
var element = $("<p id=\"" + this.UrlTitle +"\">" + this.Name + "</p>").live('click',function () { alert('hello from binded function call') });
dataList.append(element);
});
“res” is just a JSON object which is well formed and i can see the p elements in my html well created too.
My issue is that when i click in a paragraph i get 3 alerts execution (the “res” elements has a length of 3), and its like the binding is done three times foreach p element.
What is causing this behaviour?
You cannot use
.liveon a DOM element (which is created from the HTML string in this case)..liveonly works with selectors. See the list of drawbacks in its documentation.I don’t see a reason to use event delegation at all here, just bind the event handler directly to the element using
.onor the shorthand.click(did some extra refactoring ;)):