Javascript: assign event listeners to elements dynamically added in a loop

I’m having trouble figuring out how to assign event listeners to html elements i’m dynamically creating in a loop within my javascript function.

My code works but only the last element added has the listener assigned and does what it should when clicked.

My ‘code’ variable is being properly assigned (to the last dynamically added element only of course), so it must have something to do with how i’m assigning the listener…?

code:

function updateDisplay(){
var cartDiv = document.getElementById('cartContents');
cartDiv.innerHTML = "";


if(myCart.length > 0)
{
for(i=0; i<=myCart.length; i++)
{
var iCode = myCart*.code;


cartDiv.innerHTML += "<div class='cartItem'><strong>"+iCode+"</strong><br/>  "+myCart*.name+"<div class='cartItemQty'>"+myCart*.qty+"</div><div id='"+iCode+"'></div><img src='images/design/oneGray.gif' width='260' height='1'/></div><br/>";


var trgDiv = document.getElementById(iCode);
this["removeBtn"+i] = document.createElement("button");
this["removeBtn"+i].innerHTML = "remove";
this["removeBtn"+i].code = iCode;


this["removeBtn"+i].addEventListener("click", function(){ removeFromCart(this.code);}, false);
trgDiv.appendChild(this["removeBtn"+i]);


}
cartDiv.innerHTML += "<br/><div class='cartBtn'><button border='0' onClick='placeOrder()' style='width: 91px; height: 27px;'>place order</button></div>";
}else{
//array has no items
cartDiv.innerHTML = "cart empty - add items";
}




}