获取jQuery插入的DOM元素,而不必在插入后对元素进行重新查询 [英] Getting jQuery-inserted DOM elements without requerying for element after insertion

查看:69
本文介绍了获取jQuery插入的DOM元素,而不必在插入后对元素进行重新查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用 jQuery 在DOM中插入任何内容,如下所示:

  $('#someselector')。prepend('< img src =/ img / myimage.gifid =someid/>'); 

有没有办法在jQuery中获取一个 jQuery 对象引用这个新图像,而不必像

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

???

解决方案

您可以尝试以下方式:

  $('#someselector')
。 prepend('< img src =/ img / myimage.gifid =someid/>')
.find('#someid');

或者只有一个img:

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

或者:

 code> $('< img src =/ img / myimage.gifid =someid/>').prependTo('#someselector')


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');

???

解决方案

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')

这篇关于获取jQuery插入的DOM元素,而不必在插入后对元素进行重新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆