JQuery:创建图像和div,然后将图像附加到div

时间:2016-06-25 12:09:38

标签: javascript jquery

我想创建一个图像对象,然后是div对象,将图像附加到div,最后将结果附加到包装器。

我这样做了:

var image = $(document.createElement('img'));
image.attr('src', url);
image.attr('id', 'preview_gallery_image_' + i);
image.addClass('admin-hotel-gallery-image');
var imageDiv = $(document.createElement('div'));
imageDiv.addClass('col-sm-3');
imageDiv.attr('id', 'preview_gallery_image_wrapper_' + i);
var imageNode = image.appendTo(imageDiv);
var finalElement = imageNode.appendTo("#gallery-wrapper");

为了使它更清晰,最终结果应如下所示:

<div id="gallery-wrapper>
    <div class="col-sm-3" id="preview-gallery-image-wrapper-1">
        <img url="...">
    </div>
</div>

我得到的只是图库包装中的图像,但图像周围的内部图像缺失:

<div id="gallery-wrapper>
    <img url="...">
</div>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

DEMO LINK

js代码

var url = 'url';
var i =1 ;

var image = $('<img />', { 
 id:'preview_gallery_image_' + i,
 class: 'admin-hotel-gallery-image' ,
 src: url
});

var imageDiv = $('<div >',{
  id: 'preview_gallery_image_wrapper_' + i
});

image.appendTo(imageDiv);



var finalElement = $('<div/>',{
  id: 'gallery-wrapper' 
});

imageDiv.appendTo(finalElement);
finalElement.appendTo('body');

<强>结果:

<div id="gallery-wrapper">
    <div id="preview_gallery_image_wrapper_1">
        <img src="url" class="admin-hotel-gallery-image" id="preview_gallery_image_1">
    </div>
</div>