简体   繁体   中英

How to Append a div with javascript inside

I have this

<div id="inprog_table">
</div>

I tried this to insert

  var div = document.getElementById('inprog_table');
  div.innerHTML = div.innerHTML+
      "<div class='row'>
              <div class='col-xs-7'>
                 "+ $(".row.active .col-xs-7 p:first-child").text()+"  
              </div>
              <div class='col-xs-2'>
                  "+ $(".row.active .col-xs-7 p:last-child").text()+"
              </div>

              <div class='col-xs-2'>
                1
              </div>"

inside inprog_table div. I know it's really wrong, but I don't know how to append all of this.

String literals in JavaScript cannot extend through multiple lines, you'll have to make each string end on the same tine it started or escape the new line with a \\

var div = $('#inprog_table');
div.append( "<div class='row'>"+
              "<div class='col-xs-7'>"+
                $(".row.active .col-xs-7 p:first-child").text() + 
              "</div>" +
              "<div class='col-xs-2'>" +
                $(".row.active .col-xs-7 p:last-child").text()+
              "</div>"+
              "<div class='col-xs-2'>1</div>"+
            "</div>");

Use .append()

$('#inprog_table').append("<div class='row'><div class='col-xs-7'>" + $(".row.active .col-xs-7 p:first-child").text() + "</div><div class='col-xs-2'>" + $(".row.active .col-xs-7 p:last-child").text() + "</div><div class='col-xs-2'>1</div>");

Use .html()

$('#inprog_table').html(function (_, old_html) {
    return old_html + "<div class='row'><div class='col-xs-7'>" + $(".row.active .col-xs-7 p:first-child").text() + "</div><div class='col-xs-2'>" + $(".row.active .col-xs-7 p:last-child").text() + "</div><div class='col-xs-2'>1</div>"
});

Use jQuery for this stuff. Pure Javascript is just too much of a hassle.

Here's the code in jQuery:

$('#inprog_table').html(
    '<div class="row">' +
        '<div class="col-xs-7">' +
            $(".row.active .col-xs-7 p:first-child").text() +  
        '</div>' +
        '<div class="col-xs-2">' +
            $(".row.active .col-xs-7 p:last-child").text() +
        '</div>' +
        '<div class="col-xs-2">1</div>' +
    '</div>'
);

You can either use:

.append()-

Ex: $("#div1").append(Element to append)

Or

.after()-

Ex: $("#div1").after(Element to append)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM