I have code similar to this:
<div id="content">
<div id="child1"></div>
<div id="child2"></div>
</div>
I am using jQuery click events
$('#child1').click(function(){
var page = "value1";
$('#content').hide();
$('#content').load('includes/'+ page +'.php', function () {
$('#content').fadeIn(speed);
});
return false;
});
However, when clicking on any of the content in the loaded #content ID the div children return the parent ID. How can I select the child ID while ignoring the parent?
The actual HTML is more complicated so the value of the child on the page wouldn’t simply be #content#child1, is there a way to have the JS ignore #content and see #child1?
If I use code like
$('div').click(function(){
alert($(this).attr("id"));
return false;
});
the value returned when clicking “#child1” or is “#content”.
I may be reading this wrong, but you’ve completely overwritten the the contents of
#content. The#child1and#child2divs no longer exist once the load command has completed.Even if your loaded data includes a
#child1div, it is not the same DOM node that you originally attached the click event to. That old node is gone, replaced by your loaded data, and the event handlers are gone too.If you want to keep listening to
#child1.click()events after the old child nodes are deleted, you have two options:#contentnodeEvent delegation allows you to bind a listener on
#contentthat will fire when events bubble up from the child elements:This will effectively keep your
#child1click handler alive even after you have replaced the nodes with totally new HTML.