Clearest way to build html elements in jQuery

前端 未结 10 1187
一个人的身影
一个人的身影 2020-12-12 11:12

I\'ve seen a lot of different styles (and few different methods) of creating elements in jQuery. I was curious about the clearest way to build them, and als

10条回答
  •  甜味超标
    2020-12-12 12:03

    This is adapted from Baer's answer. I find it more readable, no need to create and join an array, no need to put quotes around every line:

    http://jsfiddle.net/emza5Ljb/

    var html =
    
        '                                                           \
          
    \
    \
    \ \
    \
    \ ' // using jQuery: // var dom = $( html ) // or if you need performance, don't use jQuery // for the parsing. // http://jsperf.com/create-dom-innerhtml-vs-jquery // var div = document.createElement( 'div' ) div.innerHTML = html var dom = $( div )

    FYI, when performance isn't an issue and elements contain a lot of dynamic data, I sometimes just write code like this (note that closure compiler will throw a warning about the unquoted class property, but in modern browsers this works fine):

    $(
          ''
    
        , {
               text     : this.fileName
             , href     : this.fileUrl
             , target   : '_blank'
             , class    : 'file-link'
             , appendTo : this.container
          }
    )
    

提交回复
热议问题