开发者

Append element2 to element1 before appending element1 to document

I'm looking to create an element dynamically with jQuery and put another element dynamically within that, but before I append it.

For example, I want the output to look like so:

<span class="imageContainer">开发者_运维知识库
    <p>Close</p>
    <img src="image.jpg" />
<span>

I could use the following, but it prevents me from using the other method of supplying the attributes:

$('<span class="imageContainer"><p>Close</p><img src="image.jpg" /></span>').prependTo('body');

I'm currently creating the span element with this code, and would like to know how I can append code to it before I append it to anything, this is probably a simple solution that I'm just overlooking:

$('<span/>', {
    'id': 'imageContainer'
});

The reason I want to use this method, is so I can attach click methods and such in one go.

UPDATED SOLUTION (thanks to @ParvSharma):

function hoverBox( url, e ) {
    var hoverbox = $( '<span/>', {
        'id': 'imageContainer',
        'style': 'top:'+e.pageY+'px; left:'+e.pageX+'px;'
    }).append(
        $('<p/>', {
            html: 'Close',
            click: function() {
                var parentContainer = '#'+$(this).parent().attr('id');
                destroy( parentContainer );
            }
        })
    ).append(
        $('<img/>', {
            'src': url
        })
    );
    return hoverbox;
}


  1. make the span

    var span = $('<span/>', { 'id': 'imageContainer'});

  2. then just do

    span.append($("<p></p>"));

  3. then jo

    span.append($("<img></img>"));

  4. now append span to anything u want to append it to


Try this:

$('<span class="imageContainer"><p>Close</p><img src="image.jpg" /></span>')
    .find('p')
        .click(function() {
            // click code here.
        })
    .end()
    .prependTo('body');


Try this

$('<span class="imageContainer"><p>Close</p><img src="image.jpg" /></span>').find("img").attr({}).end().prependTo('body');

You can also use this based on your requirement.

$('<span/>', {
    'id': 'imageContainer'
}).append('<p>Close</p><img src="image.jpg" />')
.prependTo('body');


$('<span/>', {'id':'theId'}).click(....);

Once you create an element with jQuery it returns jQuery object of it...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜