jQuery在div标签内添加图像

问题描述 投票:147回答:6

我有一个div标签

<div id="theDiv">Where is the image?</div>

我想在div中添加一个图像标签

最终结果:

<div id="theDiv"><img id="theImg"  src="theImg.png" />Where is the image?</div>
jquery
6个回答
296
投票

您是否尝试过以下方法:

$('#theDiv').prepend('<img id="theImg" src="theImg.png" />')

50
投票

我的2美分:

$('#theDiv').prepend($('<img>',{id:'theImg',src:'theImg.png'}))

22
投票
$("#theDiv").append("<img id='theImg' src='theImg.png'/>");

您需要阅读文档here


10
投票

如果我们想在调用<div>is函数时更改image()标记的内容,我们必须这样做:

使用Javascript

function image() {
    var img = document.createElement("IMG");
    img.src = "/images/img1.gif";
    $('#image').html(img); 
}

HTML

<div id="image"></div>
<div><a href="javascript:image();">First Image</a></div>

4
投票

除了Manjeet Kumar的帖子(他没有声明)

var image = document.createElement("IMG");
image.alt = "Alt information for image";
image.setAttribute('class', 'photo');
image.src="/images/abc.jpg";
$(#TheDiv).html(image);

1
投票
var img;
for (var i = 0; i < jQuery('.MulImage').length; i++) {
                var imgsrc = jQuery('.MulImage')[i];
                var CurrentImgSrc = imgsrc.src;
                img = jQuery('<img class="dynamic" style="width:100%;">');
                img.attr('src', CurrentImgSrc);
                jQuery('.YourDivClass').append(img);

            }
© www.soinside.com 2019 - 2024. All rights reserved.