I have a script in jQuery/PHP, which receives other levels on the UL list. For example:
<ul class="obj">
<li>Object A</li>
<li>Object B</li>
</ul>
After click on the LI element, jQuery appends another list to this element received by POST:
<ul class="obj">
<li>Object A
<ul class="obj">
<li>Object A1</li>
<li>Object A2</li>
</ul>
</li>
</li>Object B</li>
Then when I want to click on ‘Object A1’ element and append another list to it, list appends to parent element, because both are “.obj li” elements..
My jQuery code:
$(function(){
$(".obj li").click(function(){
var el = $(this);
$.post('get_rel.php',
function(data){
$(el).append(data)
el = null;
});
})
})
How to invoke a click event exactly on the clicked (child) element?
Thanks for help.
What’s causing this is the
click()handler is only being bound to the elements on the page at the time you callclick(). When you add child elements to the list, the click event is bubbling up to the top levelli, and the event handler is been triggered. Here,thisis the top levelli, which is why the new elements are appearing.Instead, you should use event delegation, which will fire for all current and future elements, and
thisinside the handler will be the current element (the important part in this case).on()was introduced in 1.7, so if you’re using an older version (and can’t upgrade), you should usedelegate():