如何使用 JQuery 创建一个新的 img 标记,使用 JavaScript 对象中的 src 和 id?

我从基本意义上理解 JQuery,但对它来说绝对是新手,并且怀疑这非常容易。

我在一个 JSON 响应中获得了图像 src 和 id (转换为一个对象) ,因此在 response seObject.imgurl 和 response seObject.imgid 中获得了正确的值,现在我想用它创建一个图像并将其附加到一个 div (让我们称之为 <div id="imagediv">)。我对动态构建 <img src="dynamic" id="dynamic">有点困惑——我看到的大多数示例都涉及替换现有映像上的 src,但我没有现有映像。

196487 次浏览

In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:

var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));

You save some bytes by avoiding the .attr altogether by passing the properties to the jQuery constructor:

var img = $('<img />',
{ id: 'Myid',
src: 'MySrc.gif',
width: 300
})
.appendTo($('#YourDiv'));

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');


myImage.attr('width', 300);
myImage.attr('height', 300);
myImage.attr('class', "groupMediaPhoto");
myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.