I understand JQuery in the basic sense but am definitely new to it, and suspect this is very easy.
我从基本的角度理解了JQuery,但是对它来说是全新的,并且怀疑这是很容易的。
I've got my image src and id in a JSON response (converted to an object), and therefore the correct values in responseObject.imgurl and responseObject.imgid, and now I'd like to create an image with it and append it to a div (lets call it <div id="imagediv">
. I'm a bit stuck on dynamically building the <img src="dynamic" id="dynamic">
- most of the examples I've seen involve replacing the src on an existing image, but I don't have an existing image.
我在JSON响应中获得了图像src和id(转换为对象),因此在responseObject中得到了正确的值。imgurl responseObject。imgid,现在我想用它创建一个图像并将它附加到一个div(让我们称它为
4 个解决方案
#1
118
In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:
在jQuery中,可以通过将HTML字符串传递给构造函数来创建一个新元素,如下所示:
var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');
#2
77
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));
#3
15
You save some bytes by avoiding the .attr
altogether by passing the properties to the jQuery constructor:
通过将属性传递给jQuery构造函数,可以避免.attr,从而节省一些字节:
var img = $('<img />',
{ id: 'Myid',
src: 'MySrc.gif',
width: 300
})
.appendTo($('#YourDiv'));
#4
2
For those who need the same feature in IE 8, this is how I solved the problem:
对于那些在IE 8中需要相同功能的人,我就是这样解决这个问题的:
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.
我不能强迫IE8在构造函数中使用object。
#1
118
In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:
在jQuery中,可以通过将HTML字符串传递给构造函数来创建一个新元素,如下所示:
var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');
#2
77
var img = $('<img />', {
id: 'Myid',
src: 'MySrc.gif',
alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));
#3
15
You save some bytes by avoiding the .attr
altogether by passing the properties to the jQuery constructor:
通过将属性传递给jQuery构造函数,可以避免.attr,从而节省一些字节:
var img = $('<img />',
{ id: 'Myid',
src: 'MySrc.gif',
width: 300
})
.appendTo($('#YourDiv'));
#4
2
For those who need the same feature in IE 8, this is how I solved the problem:
对于那些在IE 8中需要相同功能的人,我就是这样解决这个问题的:
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.
我不能强迫IE8在构造函数中使用object。