开发者

get the html element after created

i'm creating a img when i click in a input, then i get the html or anyelse from the created img.

but i dont know why t开发者_JAVA百科his is not working!

always return null

my js:

$("#click").click(function(){
    var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
    $(this).after($imgDone);
    setTimeout(function(){
          alert($(this).next().html());
    }, 1000);
});

i mande a exp.: Demo


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/


because the timeout function is called form a different context, this no longer applies.

$("#click").click(function(){
    var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
    $(this).after($imgDone);
    myImg = $(this);
    setTimeout(function(){
          alert($(myImg).next().html());
    }, 1000);
});


The ".html()" method gets the contents of something, not including the markup for the container itself.

The other answers indicating that the use of this in the timeout handler are correct, of course. When you fix that, however, the alert will just be empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜