Create HTML tag from Javascript object

前端 未结 6 2077
清歌不尽
清歌不尽 2021-02-19 06:21

What is the best method to change this object

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

into a valid HTML tag string like t

6条回答
  •  旧巷少年郎
    2021-02-19 06:39

    Why not:

    $('', 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.

提交回复
热议问题