I have a table structure like this:
<table>
<tr>
<td>
<ul>
<li class="check"></li>
</ul>
</td>
<td>
<ul>
<li class="check"></li>
<li class="check"></li>
</ul>
</td>
</tr>
</table>
My goal is, on click within a table cell, another li element is added to the single ul within each cell. When clicking ON the li element, the last li in the cell’s ul is removed.
Here is the jq I tried:
$(document).on("click", "table tr td", function() {
var parul = $(this).children("ul");
$('<li class="check"> </li>').appendTo(parul);
});
$(document).on("click", "li.check", function(){
$(this).siblings(":last").remove();
});
The table is being generated by jQ dynamically, so I’m trying to avoid using IDs in my selectors. Also why I’m using .on(), since as I understand, it will apply to LIs that don’t necessarily exist yet (please correct me if I’m understanding that incorrectly!).
I’ve found that the above 2 functions work independently, but when I uncomment both of them, only the “adding” function works, the remove doesn’t.
I’m new to jQ, so this is a real mystery. If there’s a totally different solution that accomplishes the same goal, I wouldn’t mind, but for learning purposes, I’d also like to understand why my code isn’t working as I expected.
Thanks in advance!
When you click on the
li, thetdregisters a click as well. You need to addstopPropagation()on thelihandler:Demo: http://jsfiddle.net/uLCRd/
This will prevent the second handler from being called once the
liclick is handled.