如何使用来自 JavaScript 对象的 src 和 id 使用 JQuery 创建新的 img 标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8013792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:23:16  来源:igfitidea点击:

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

javascriptjqueryimage

提问by Peter

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">。我有点坚持动态构建<img src="dynamic" id="dynamic">- 我见过的大多数示例都涉及替换现有图像上的 src,但我没有现有图像。

回答by Rob W

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

回答by Frenchi In LA

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

回答by ErickBest

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

您可以.attr通过将属性传递给jQuery 构造函数来避免完全使用,从而节省一些字节:

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

回答by Vedran Maricevic.

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