Set same color as prev row if data matches otherwise different color when rows are dynamically created
I need to set same color as previous row if data matches otherwise use a different color when rows . The code works if the rows, cells and text within cells are hardcoded as here https://codereview.stackexchange.com/questions/121593/set-same-color-as-prev-row-if-data-matches-otherwise-different-color but produces alternating colouring when the rows, cells and text are dynamically generated.
$(document).ready(function () {
var c = 0;
$("#tblExport tbody tr").each(function () {
var $item = $("td:first", this);
var $prev = $(this).prev().find('td:first');
if ($prev.length && $prev.text().trim() != $item.text().trim()) {
c = 1 - c;
}
$(this).addClass(['zebra-even', 'zebra-odd'][c]);
});
});
#tblExport>tbody {
font: normal medium/1.4 sans-serif;
}
#tblExport {
border-collapse: collapse;
width: 100%;
}
#tblExport th,td {
padding: 0.25rem;
text-align: left;
border: 1px solid #ccc;
}
#tblExport th {
background: #bfbfbf;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
{% for product in products %}
<tr>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
</tr>