Create HTML tag from Javascript object

前端 未结 6 2072
清歌不尽
清歌不尽 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:44

    Here's how you make it as a string:

    var img = '

    http://jsfiddle.net/5dx6e/

    EDIT: Note that the code answers the precise question. Of course it's unsafe to create HTML this way. But that's not what the question asked. If security was OP's concern, obviously he/she would use document.createElement('img') instead of a string.

    EDIT 2: For the sake of completeness, here is a much safer way of creating HTML from the object:

    var img = document.createElement('img'),
        obj = { src : 'img.jpg', title: 'foo' };
    
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        img.setAttribute(prop, obj[prop]);
      }
    }
    

    http://jsfiddle.net/8yn6Y/

提交回复
热议问题