admin管理员组文章数量:1418371
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.
本文标签: javascriptCreating dynamic spanStack Overflow
版权声明:本文标题:javascript - Creating dynamic span - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745288276a2651633.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论