I've come to maintain a piece of javascript that downloads some JSON data from the server, builds a new table row (like $('<tr></tr')
) and inserts it into the document.
The a
node is, at one point created like this:
var a = $('<a class="foo" href="#"></a>');
and later, an event is bound to it like this:
a.click(function () {
// yadda yadda
return false;
});
The only problem is that this doesn't seem to work. Neither does binding through on()
or the deprecated live()
. The handler is simply "ignored", never fires and the page scrolls to the top (due to the href="#"
). When binding the event, the element is already append
ed to DOM. Any help would be greatly appreciated.
Some contextual information that comes to mind: the element is created inside a loop iterating over the data, but that shouldn't be a problem unless javascript has some really weird stuff going on with scoping, plus everything else I try with the element works: I can change its content, styling, only the event binding doesn't work. And of course, the jQuery version, which is 1.8.3.
EDITED
The .on() should be set up like this to work with dynamically created elements. Also, make sure to use Jquery version 1.8 (newest release)
Also, you need to prevent the standard action of the click if you don't want to scroll to the top.
Here is a working FIDDLE
var a = $('<a class="foo" href="#">ASD</a>');
a.appendTo($("body"));
$('body').on('click', 'a', function(e) {
e.preventDefault();
$(this).after('<br/><a class="foo" href="#">ASD</a>');
});