简体   繁体   English

如何将按钮动态附加到div

[英]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 这是动态加载div数据

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. 它正确地循环通过,但只显示第一个对象。(即,我在数组中有6个名称,但仅显示第一个名称)。为什么?我也尝试通过添加滚动和高度来进行尝试。

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() html() clears all existing content and applies whatever you provided in its place. html()清除所有现有内容并应用您提供的任何内容。 This is why only the last item in your loop is visible. 这就是为什么循环中只有最后一项可见的原因。

To fix this, use append() instead. 要解决此问题,请改用append()

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. 您可以使用相同的方法append() ,将第二个示例中的内容也添加到DOM中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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