Appending multiple html elements using Jquery

后端 未结 5 2072
醉话见心
醉话见心 2021-02-08 02:10

Am new to jQuery and wondering if any could advise me on best practise...

I am looking to append a div element to the page, which contains a lot of html and not sure wha

5条回答
  •  無奈伤痛
    2021-02-08 02:25

    With ES6 (ECMAScript 2015) you can now use the backticks to surround all the HTML even with single or double quotes (useful also to add variables inbetween).

    However, since the question seemed to focus on adding the entire block after some existing element, perhaps the after method would be more suitable than the append one in this case. This is the difference between them (run the snippet):

    let $num = 0;
    $('main').append(`
      

    Appended ${++$num}

    Using 'single' and "double-quotes" without escaping!

    Appended ${++$num}

    Using 'single' and "double-quotes" without escaping!

    `).after(`

    Added after main

    ${++$num} blocks of multiple elements were added through jQuery

    `);
    article {background: #eee;border:1px solid #000;padding:1rem}
    main {background: #ccc;padding:1rem}
    body {background: #aaa;padding:1rem}
    
    

    Main section

    jQuery

    Adding multiple elements...

    Note

    You can also use the equivalent insertAfter and appendTo if you prefer this alternative syntax: $('

    my html

    ').insertAfter('main')

    The jQuery object containing the HTML blocks to add goes first and you only need to reference the string in the method's parameter.

提交回复
热议问题