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

后端 未结 3 920
北恋
北恋 2021-01-18 09:05

Assuming I insert anything in my DOM with jQuery, like so:

$(\'#someselector\').prepend(\'\');

相关标签:
3条回答
  • 2021-01-18 09:21

    Make it into an jQuery object before prepending it:

    var $img = $('<img src="/img/myimage.gif" id="someid" />');    
    $('#someselector').prepend($img);    
    $img.foo();
    
    0 讨论(0)
  • 2021-01-18 09:24

    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')
    
    0 讨论(0)
  • 2021-01-18 09:25

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

    var $img = $('#someselector')
                .prepend('<img src="/img/myimage.gif" />')
                .find(':first');    
    
    0 讨论(0)
提交回复
热议问题