I have an AJAX callback that returns a list of results that are written out as links within a specific div
. The code goes something like this:
$.each(data, function (idx, item) {
var a = document.createElement("a");
a.innerText = item.name;
a.href = "#";
// TODO set handler for click event
d.appendChild(a);
d.innerHTML += "<br/>";
});
This works fine, and the links appear. However, I want to perform some actions when the links are clicked. item
has some other properties that I will need in the click handler, so I would like to close over them. Here's a definition of the handler:
// defined in loop as a closure
var clickHandler = function() {
$('#siteId').value = item.siteId; // closed over this property
$('#siteName').value = item.name; // and this one
return false;
};
I have tried a few methods of providing this handler for the click event. Firstly:
a.onclick = clickHandler;
Secondly:
a.addEventListener("click", clickHandler, true);
I've also tried mouseup
, mousedown
events, but they don't work either.
The behaviour I see is that the browser navigates to the #
anchor (it is appended to the URL).
What is going on here? Also, is there a jQuery solution that'd be more robust across browsers?