如何使用JQuery创建一个新的img标记,以及来自JavaScript对象的src和id? [英] How to create a new img tag with JQuery, with the src and id from a JavaScript object?
问题描述
我理解基本意义上的JQuery,但我肯定是新手,并且怀疑这很容易。
I understand JQuery in the basic sense but am definitely new to it, and suspect this is very easy.
我的图像src和id是JSON响应(转换为对象),因此在responseObject.imgurl和responseObject.imgid中的值正确,现在我想用它创建一个图像并将其附加到div(让我们称之为< div id =imagediv>
。我有点卡在动态构建< img src =dynamicid =dynamic>
- 我见过的大多数例子涉及替换现有图像上的src,但我没有现有图像。
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.
推荐答案
在jQuery中,可以通过将HTML字符串传递给构造函数来创建新元素,如下所示:
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');
这篇关于如何使用JQuery创建一个新的img标记,以及来自JavaScript对象的src和id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!