I’m having an issue using .on() to appended elements.
I’m trying to select and dynamically create divs that have the ability to be selected and have divs added to them. The problem I’m having is that when I select a dyanmic element that is inside an element that uses .on()it selects the parent too. I’m fairly new to jQuery so there may be a totally better solution.
<script type="text/javascript">
$(function () {
var wrapper = $('#wrapper');
var add_row_button = $('#add_row');
var row_count = 0;
var selected_item = wrapper;
add_row_button.click(function () {
row_count++;
var new_element = '<div id="' + row_count + '">' + row_count + '</div>';
selected_item.append(new_element);
$('#' + row_count).on("click", function () {
console.log(selected_item);
selected_item.removeClass("selected");
selected_item = $(this);
selected_item.addClass("selected");
console.log(selected_item);
});
});
});
<button id="add_row">Add row</button>
<div id="wrapper"></div>
You haven’t shown us your actual HTML, but here’s an example that could work for you.
The idea of delegated event handling is that you attach an event handler to a parent object that is static (doesn’t come and go). Events on child objects then bubble up to the parent and the jQuery event handler on the parent checks the source of the event to see if it matches the desired selector.
So, if your container for these dynamically created events was
#containerand each dynamically create child had a class name ofdynChild, you could hook up a click handler for all children matching that criteria with this:You can then add/remove matching child objects without changing the event handling and their click events will automatically be handled by this delegated event handler on the parent object. It’s one of the more powerful capabilities for managing dynamically created/modified pages simply.