jQuery在div标签内添加图像


154

我有一个div标签

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

我想在div内添加图片标签

最终结果:

<div id="theDiv"><img id="theImg"  src="theImg.png" />Where is the image?</div>

Answers:


301

您是否尝试过以下方法:

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

10
我无法对以上的Jose Basilio做出回应(代表人数不足),但在“图片在哪里?”之后附加附加。前置将放置在前面。
Topher Fangio

4
我本来要为您使用前置功能投票的,但我注意到您在选择器中缺少“#” ...
Ben Koehler 2009年

1
我跳了一下枪。接得好。+1
何塞·巴西里奥

appendTo不起作用...至少在我的代码中,即使在发布此线程之前,我在jQuery docs页面上阅读它后,也不是正确的选择。
PositiveGuy 2010年

尝试使用.append()和.html()添加image标记,但是尽管<img>标记正确显示在源中,但图像未加载。有什么建议吗?
AnoopGoudar '17

52

我的2美分:

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

我喜欢$('<img>')用法的答案,正在寻找它。
user734028 '04

您还可以在$('<img')。attr('id','theImg')。attr('src','theImg.png')
Scott


10

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

Java脚本

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>

1
我建议您添加一些解释。
2014年

1
如果要更改<div>标记的内容,则无论何时调用函数image()。我们必须这样做/函数image(){var img = document.createElement(“ IMG”); img.src =“ /images/img1.gif”; $('#image')。html(img); } <div id =“ image”> </ div> <div> <a href="javascript:image();">第一个图像</a> </ div>
Manjeet Kumar 2014年

6

除了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);

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

            }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.