开发者

Getting jQuery-inserted DOM elements without requerying for element after insertion

Assuming I insert anything in开发者_运维技巧 my DOM with jQuery, like so:

$('#someselector').prepend('<img src="/img/myimage.gif" id="someid" />');

Is there a way in jQuery to get a jQuery object referencing this new image, without having to do an extra search like

var myImage = $('#someselector #someid');

???


Make it into an jQuery object before prepending it:

var $img = $('<img src="/img/myimage.gif" id="someid" />');    
$('#someselector').prepend($img);    
$img.foo();


You can try something like this:

$('#someselector')
    .prepend('<img src="/img/myimage.gif" id="someid" />')
    .find('#someid');

Or if there's only one img:

$('#someselector')
    .prepend('<img src="/img/myimage.gif" id="someid" />')
    .find('img');

Alternatively:

$('<img src="/img/myimage.gif" id="someid" />').prependTo('#someselector')


Solution without creating a jQuery object before and without having an Id:

var $img = $('#someselector')
            .prepend('<img src="/img/myimage.gif" />')
            .find(':first');    
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜