I am unable to get the click event to work for elements created thusly.
http://jsfiddle.net/iambriansreed/PEZXa/
jQuery
$('<a href="#">a</a>', {
click: function(){
alert('a clicked');
}
}).appendTo("div");
$('<span>span</span>', {
click: function(){
alert('span clicked');
}
}).appendTo("div");
Please don't show me the 50 different ways you can add an onclick
event to an element I want to know why this particular method does or does not work.
From the docs: http://api.jquery.com/jQuery/#jQuery2
$('<a />', {
href: '#',
text: 'a',
'click': function(){
alert('a clicked');
}
}).appendTo("div");
$('<span />', {
text: 'span',
'click': function(){
alert('span clicked');
}
}).appendTo("div");
http://jsfiddle.net/PEZXa/56/
From the docs
html - A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).
jQuery doesn't seem to like it when elements that are created like this contain text nodes or attributes. In essence, the HTML code you provide should be a single (possibly self-closing) tag.
This is probably because you are using a syntax that expects the attributes to be defined within the object parameter, not mixed between the HTML and the object.
Anyways, this code works for me:
$('<a /> ', {
href: '#',
text: 'a',
click: function() {
alert('a clicked');
}
}).appendTo("div");
$('<span />', {
text: 'span',
click: function() {
alert('span clicked');
}
}).appendTo("div");
Demo: http://jsfiddle.net/PEZXa/60/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With