I\'ve come to maintain a piece of javascript that downloads some JSON data from the server, builds a new table row (like $(\'
) and inserts i
Try this:
var a = $('<a class="foo" href="#">ASD</a>');
$("body").html(a);
a.click(function() {
alert('a');
return false;
});
You can use event delegation like so.
$('body').on('click','.foo',function(){
alert('foo');
});
This will allow you to set the event handler before the element is present.
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>');
});
You have various options. You can bind to the element or to the document.
BIND TO DOCUMENT:
$(document).on("click", "a.foo", function(event){
//do stuff here
});
When you bind to a document, you can freely create and destroy a.foo elements and they will all respond to your function.
BIND TO ELEMENT:
$("a.foo").on("click", function(event){
//do stuff here
});
When you bind to an element, the function is bound to all previously existing elements ONLY. So make sure you do this at the end of document load or at the end of your function.
I would recommend always binding to document!
Try binding the function within the scope of the function where you dynamically create the element.
$('a.foo').on('click',function(event){
//your code goes here
});
Two things come to my mind:
Here there is a fiddle that works with code very similar to yours.
var a = $('<a class="foo" href="#">ASD</a>');
a.click(function() {
alert('a');
});
a.appendTo($("body"));