This may not be possible because it $(this)refers to the object windowin this case, and not to the element <a>. The link thiswill be properly linked to the newly created element only if called in the context of the function.
There may be a way to insert an element in thisusing closures, but I can't figure out how interesting it is, can anyone come up with a solution.
Until then, this alternative is less elegant, but will always work:
mylink = $('<a>', {
id: 'test',
click: function(){
alert($(this).width());
return false;
}
}).appendTo($("body")).html("Test");;
mylink.css({ left: mylink.width() / 2});
Jsfiddle
source
share