Clearest way to build html elements in jQuery

前端 未结 10 1174
一个人的身影
一个人的身影 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 =
    
        '                                                           \
          <div>                                                     \
            <div class="js-alert-box"></div>                        \
            <form id="my-form-to-validate">                         \
              <input id="login-username" name="login-username">     \
            </form>                                                 \
          </div>                                                    \
        '
    
    // 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):

    $(
          '<a></a>'
    
        , {
               text     : this.fileName
             , href     : this.fileUrl
             , target   : '_blank'
             , class    : 'file-link'
             , appendTo : this.container
          }
    )
    
    0 讨论(0)
  • 2020-12-12 12:06

    Simplest way of doing this -

    var optionsForLength = 
    '<option value="Kilometre">Kilometre</option>'+
    '<option value="Metre">Metre</option>'+
    '<option value="Centimetre">Centimetre</option>'+
    '<option value="Milimetre">Milimetre</option>'+
    '<option value="Micrometre">Micrometre</option>'+
    '<option value="Nanometre">Nanometre</option>'+
    '<option value="Mile">Mile</option>'+
    '<option value="Yard">Yard</option>'+
    '<option value="Foot">Foot</option>'+
    '<option value="Inch">Inch</option>'+
    '<option value="Nautical mile">Nautical mile</option>';
    
    0 讨论(0)
  • 2020-12-12 12:08

    After looking around for a while, I found the style which I finally settled on. First, I'll say that I used Mustache for templating, and it worked well. Sometimes, though, you just need to build an element one time, without reusing it, or have some other motivation to not bring in another library. In this situation, I have taken to using:

    $("body")
    .append(
        $("<div>")
        .append(
            $("<div>")
            .append(
                $("<h1>").text(title)
            )
        )
        .append(
            $("<div>").text(content)
        )
    );​
    

    This works because append() returns a reference to the object you're appending to, so chained append()s attach to the same object. With proper indentation, the structure of the markup is obvious, and this way it's easy to modify. Obviously this is slower than using templates (the whole thing has to be built piece by piece), but if you're only using it for initialization or something similar then it is a great compromise.

    There are many ways one could format a construct like this, but I've chosen a way to make it clear what's going on. The rule I used is that there should be a maximum of one opening parenthesis and/or one closing parenthesis on each line. Also, the leaves of these append trees do not need to be passed to the jQuery constructor, but I've done so here for visual repetition.

    0 讨论(0)
  • 2020-12-12 12:14

    Templates are great and if you have access to them in your project, I suggest you use them. If you're using Underscore or Lodash it's built in. In some cases however, you will need to build HTML in your code whether it's refactoring or testing. I've found that the below format is the clearest to read when that is the requirement.

    Note: The HTML spec allows single OR double quotes for attributes in your markup so don't bother with all the crazy escaping.

    this.$fixture = $([
      "<div>",
      "  <div class='js-alert-box'></div>",
      "  <form id='my-form-to-validate'>",
      "    <input id='login-username' name='login-username'>",
      "  </form>",
      "</div>"
    ].join("\n"));
    
    0 讨论(0)
提交回复
热议问题