this
is pointing at the wrong place in setInterval
.
The this
you have in the outer scope isn't the same as the this
that you get inside the callback, which will usually be the window
object, since:
setInterval(f, t)
is actually
window.setInterval(f, t);
To solve the problem, take a copy of this
in the outer scope:
$("#click").click(function(){
var self = this;
var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
$(this).after($imgDone);
setTimeout(function(){
alert($(self).next().html());
}, 1000);
});
For efficiency, as @T.J. Crowder suggests, you could actually use the jQuery constructor to take that copy, and save yourself a few calls to jQuery:
$("#click").click(function(){
var $this = $(this);
var $imgDone = $('<img/>')
.attr({src: 'someImage/insomewhere.jpg'})
.insertAfter(this); // NB: not $this here
setTimeout(function(){
alert($this.next().html());
}, 1000);
});
The other problem is that .html()
shows the inner contents of tags, not the tags themselves, and your img
tag has no inner contents.
There doesn't appear to be any builtin jQuery method that returns the actual whole HTML of an element. To do that you'd need to put your element into something else (e.g. a <div>
) and then take the .html()
of that.
Here's a plugin I just made that does this, inspired by something I found via Google:
(function($) {
$.fn.outerhtml = function() {
return $('<div/>').append(this.clone()).html();
};
})(jQuery);
Demo of it in use on your problem at http://jsfiddle.net/alnitak/qaSmS/