I have some jQuery appending HTML from a PHP script.
jQuery
$.ajax({
type: "POST",
url: "newPage.php",
data: data,
cache: false,
success: function(html)
{
$('.item1 ul').append(html);
}
});
PHP
echo"<li><a href=\"#\">".$pages["title"]."<img src=\"images/delete.jpeg\" class=\"delete del-page\" id=".$pages["pages_id"]." title=\"Delete Page\"/><img src=".$state." class=\"page-state\" id=".$pages["pages_id"]." title=\"Page On\"/></a></li>";
After appending, no jQuery events work on the new HTML.
You need to delegate your events with
.on()You can read specifically about this here
But basically you need to attach the listener higher up in the DOM heirarchy.
so instead of this…
do this
Why?
This works because the dynamic elements that are not yet on the page when you bind the events, still fire the events, they just don’t have the handlers.
Thanks to event bubbling all DOM elements up the tree will hear their descendant’s events (unless propagation has been stopped), and can act on them accordingly.
In this example, when
'.item1 ul'hears that an'event'has been triggered from one of it’s child elements, if it was'.selector'that triggered it, the handler will fire.