从Javascript对象创建HTML标签 [英] Create HTML tag from Javascript object

查看:92
本文介绍了从Javascript对象创建HTML标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是更改此对象的最佳方法

  {
src:'img.jpg',
标题:'foo'
}

转换为有效的 HTML标签字符串像这样

 < img src =img.jpgtitle =foo/> 

解决方案1 ​​



使用jQuery这很容易;但是很复杂:

  $('< img />')。attr(obj).wrap('< div />')的父()HTML()。; 

任何更好的想法?

解决方案

为什么不:

  $('< img />',obj) (0).outerHTML; 

小提琴



您不需要使用多个功能将其包装在div中,并获取html,只需使用 get(0)获取DOM元素和 outerHTML 以获取元素的html表示。



除非您使用的浏览器很旧,否则您可以依靠 outerHTML



这是一个 JSPerf 来比较方法之间的性能差异。


What is the best method to change this object

{
    src: 'img.jpg',
    title: 'foo'
}

into a valid HTML tag string like this

<img src="img.jpg" title="foo" />

Solution 1

With jQuery this is easy; but complicated:

$('<img/>').attr(obj).wrap('<div/>').parent().html();

Any better ideas?

解决方案

Why not:

$('<img/>', obj).get(0).outerHTML;

Fiddle

You do not need to wrap it in a div using multiple functions and get the html, just use get(0) to get the DOM element and outerHTML to get the element's html representation.

Unless you are using browsers really old you can rely on outerHTML

Here is a JSPerf to compare the performance diff between the approaches.

这篇关于从Javascript对象创建HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆