How do I assemble a
    using jQuery append()?

后端 未结 5 1401
谎友^
谎友^ 2020-12-29 20:17

I\'m trying to use the append function and encountered this:

$(\"#details\").append(\'
    \'); for (var i = 0; i < 10; i++) { $(\"#details\").ap
5条回答
  •  遥遥无期
    2020-12-29 21:16

    Nope, you can't use it like that. append is an atomic operation, which creates the element directly.

    // The 
      element is added to #details, then it is selected and the jQuery // selection is put in the "list" variable. var list = $('
        ').appendTo('#details'); for (var i = 0; i < 10; i++) { // New
      • elements are created here and added to the
          element. list.append('
        • something
        • '); }

    Alternatively, generate the HTML and add it all at once (this will be more similar to your original code):

    var html = '
      '; for (var i = 0; i < 10; i++) { html += '
    • something
    • '; } html += '
    '; $('#details').append(html);

    This code is noticeably faster when dealing with many elements.

    If you need a reference to the list, just do the following instead of $('#details').append(html);:

    var list = $(html).appendTo('#details');
    

提交回复
热议问题