My click event handler is not firing on newly appended list items.
Here are my list items markup:
<ul class="list-inline product-colours">
<li id="my-sku-1" class="available">product colour 1</li>
<li id="my-sku-2" class="available selected">product colour 2</li>
<li id="my-sku-3" class="available">product colour 3</li>
<li class="not-available">product colour 4</li>
</ul>
My styling for the above list items:
.product-colours li
{
cursor: pointer;
padding: 5px;
}
.product-colours .available
{
border: 2px solid #999;
}
.product-colours .selected
{
border: 2px solid #333;
}
.product-colours .not-available
{
border: 2px solid #f00;
cursor: not-allowed;
}
I am playing around with these list items. When I click on a list item, I then execute some server code in C#
and return a JSON
result. This result I take and add additional items to the above already created list items.
Here is my jQuery
code for the click event handler:
$('.product-colours li').click(function () {
if (this.id) {
$.ajax({
data: { sku: this.id },
dataType: 'json',
url: '/MyWebsite/Product/Test'
}).done(function (data) {
var productColours = $('ul.product-colours');
$.each(data.Products, function (i, productColour) {
if (productColour.IsAvailable) {
if (productColour.IsSelected) {
productColours.append('<li id="' + productColour.SKU + '" class="available selected">' + productColour.Name + '</li> ');
}
else {
productColours.append('<li id="' + productColour.SKU + '" class="available">' + productColour.Name + '</li> ');
}
}
else {
productColours.append('<li class="not-available">' + productColour.Name + '</li> ');
}
});
}).fail(function () {
alert("error");
});
}
});
After a new list item is added by doing productColours.append()
it displays correctly. When I go and click on the appended list item the click is not picked up by the event handler. The event handler is fired from the items added when the page loaded, but it is not firing on the newly added items. Why is this?