Catching click events on <a> elements that are programmatically added to the DOM
I have an AJAX callback that returns a list of results that are written as links within a specific one div. The code looks 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 great and links appear. However, I want to perform some actions when clicking links. itemhas some other properties that I will need in the click handler, so I would like to close them. Here's the definition of a 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 tried several methods of providing this click event handler. Firstly:
a.onclick = clickHandler;
Secondly:
a.addEventListener("click", clickHandler, true);
I also tried the events mouseup, mousedownbut they do not work either.
, , , # ( URL-).
? , jQuery, ?
+3
4
- jQuery:
$.each(data, function (idx, item) {
$("<a />", { text: item.name, href: '#', click: clickHandler })
.appendTo(d).after('<br />');
});
$(html, props) , href . .appendTo(), d, <br />, , .after().
+2