I’ve come across a very strange issue that I have a workaround for, but don’t actually know why it’s happening.
Essentially, I take an existing DOM element, use innerHTML to create append DOM element, and then put in an event handler for it’s onclick event.
for(i=0; i<contextMenuModel.length; i++) {
contextMenuRow = contextMenuModel[i];
currentRowId = "edit_context_table_row_" + i;
editTable.innerHTML += "<div id='" + currentRowId + "'></div>";
row = dojo.byId(currentRowId);
row.innerHTML += "<span>" + contextMenuRow.labelName + "</span>";
row.innerHTML += "<span>" + contextMenuRow.eventName + "</span>";
dojo.connect(row, "onclick", row, rowClickHandler);
}
The problem is this: only the last row ends up with the onclick handler. The others do not. It does not matter what browser I’m in, it does not matter if I change dojo.connect to
row.onclick = rowClickHandler;
Also, if I take out the:
row.innerHTML += "<span>" + contextMenuRow.eventName + "</span>";
it still does not work.
However, the workaround that I have found (which makes this all the better) is that this works:
for(i=0; i<contextMenuModel.length; i++) {
contextMenuRow = contextMenuModel[i];
currentRowId = "edit_context_table_row_" + i;
editTable.innerHTML += "<div id='" + currentRowId + "'></div>";
row = dojo.byId(currentRowId);
row.innerHTML += "<span>" + contextMenuRow.labelName + "</span>";
row.innerHTML += "<span>" + contextMenuRow.eventName + "</span>";
}
for(i=0; i<contextMenuModel.length; i++) {
row = dojo.byId("edit_context_table_row_" + i);
dojo.connect(row, "onclick", row, rowClickHandler);
}
Such a strange problem.
I find when creating elements dynamically and attaching events to them I usually come out better using
document.createElement. This ensures your element is getting added to the dom and you have an object to work with instead of concatenating strings.