简体   繁体   中英

How to append button dynamically to a div

Here is my code

<div class="EquipmentContent row">
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 subSection" style="float:right;background:#dff0ff;">         
        <section class="col-xs-12 col-sm-1 cl-md-1 col-lg-1">
          <button type="button" style="display: inline-block;float:right;" class="btn btn-danger" onclick="hideEquipmentDetails()"><i class="fa fa-times"></i></button>
        </section>
      </div>
    </div>

Here am loading div data dynamically

var content= response.data.filters;
$.each(content,function(i,value){ 
    $('.subSection').html('<section class="col-xs-12 col-sm-2 cl-md-2 col-lg-2"><label class="equipmentHeaderlable">Name</label><label class="equipmentHeaderValues">'+value.name+'</label></section>').appendTo('.EquipmentContent');
});

Its looping through correctly but only first object is displayed.(ie I have 6 names in an array but its showing only 1st name).why so?I tried by adding scroll and height also.

One more thing how can I append this section dynamically?

<section class="col-xs-12 col-sm-1 cl-md-1 col-lg-1">
<button type="button" style="display: inline-block;float:right;" class="btn btn-danger" onclick="hideEquipmentDetails()"><i class="fa fa-times"></i></button>
    </section>

The issue is because you're using html() in a loop. html() clears all existing content and applies whatever you provided in its place. This is why only the last item in your loop is visible.

To fix this, use append() instead.

var content= response.data.filters;
$.each(content,function(i,value){ 
  $('.subSection').append('<section class="col-xs-12 col-sm-2 cl-md-2 col-lg-2"><label class="equipmentHeaderlable">Name</label><label class="equipmentHeaderValues">' + value.name + '</label></section>').appendTo('.EquipmentContent');
});

You can use the same method, append() , to add the content in your second example to the DOM too.

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