2011-05-10 85 views
6

重新查询元素假设我在DOM插入任何与jQuery,就像这样:入门jQuery的插入DOM元素,而无需插入后

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

是否有jQuery的一种方式来获得一个jQuery对象引用这个新形象,而不必进行额外的搜索,如

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

???

回答

5

你可以尝试这样的事情:

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

或者,如果只有一个IMG:

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

或者:

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

是的,最后一个是完美的。谢谢! – Sorcy 2011-05-11 06:49:58

11

使之成为一个jQuery对象前前面加上:

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

这是一个不错的解决办法,但我喜欢qwertymk更好的一个在线解决方案。 – Sorcy 2011-05-11 06:51:16

1

解决方案,而之前不具有ID创建一个jQuery对象:

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