简体   繁体   English

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

[英]How to create a new img tag with JQuery, with the src and id from a JavaScript object?

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(让我们称之为<div id="imagediv"> 。我有<div id="imagediv">在动态构建<img src="dynamic" id="dynamic"> - 我见过的大部分例子都涉及到src在现有图像上,但我没有现有图像。

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');
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 : 通过将属性传递给jQuery构造函数,可以完全避免使用.attr来节省一些字节:

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: 对于那些在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在构造函数中使用对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM