How can I create dynamic tags?
$("<img />").attr({
id: "image-1",
src: "/images/flower.png",
}).appendTo("#" + imgContainer);
It will create <img src="/images/flower.png" id="image-1" />
I want to create <span>
tag around <img>
tag.
i.e. <span><img src="/images/flower.png" id="image-1" /></span>
How can I create dynamic tags?
$("<img />").attr({
id: "image-1",
src: "/images/flower.png",
}).appendTo("#" + imgContainer);
It will create <img src="/images/flower.png" id="image-1" />
I want to create <span>
tag around <img>
tag.
i.e. <span><img src="/images/flower.png" id="image-1" /></span>
3 Answers
Reset to default 6You can use wrap()
:
$("<img />").attr({
id: "image-1",
src: "/images/flower.png"
}).appendTo("#" + imgContainer).wrap("<span />")
You can use wrap()
to wrap one element inside another. For example:
$("<img />").attr({
id: "image-1",
src: "/images/flower.png",
})
.appendTo("#" + imgContainer)
.wrap("<span />");
DOM operations are oh-so-expensive; just prepare the markup you're after and then append it as needed!
//Before:
$("<img />") //#1, create an element outside of the tree
.attr({ //#2? change its attributes
id: "image-1",
src: "/images/flower.png"
})
.appendTo("#" + imgContainer) //#3, add the element to DOM
.wrap("<span />"); //#4, create and add another element to DOM
//After:
$('<span><img src="/images/flower.png" id="image-1"></span>') //#1
.appendTo("#" + imgContainer); //#2
Here is a jsperf test case which results in ~5K ops/sec for the first case and ~14K for the latter (on my pretty decent box).
This is not premature optimization, either. If you have, for instance, ajax-populated 7x10 table and you create every cell individually... and wrap them into <tr>
elements... and then add it to a table, the overhead adds up. Operate on a string and your script will be at least 80 times faster!
Another aspect to remember is that jsperf explicitly measures javascript performance only. If you're manipulating a table, its content will be even more aggressively re-painted/re-flown.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745288276a4620697.html
评论列表(0条)