简体   繁体   English

如何动态创建和附加到DIV?

[英]How to dynamically create and append to a DIV?

I have a container #form_wrapper and I want to dynamically add inputs from an array rf_fields . 我有一个容器#form_wrapper ,我想从数组rf_fields动态添加输入。 Assume the value of the array is var rf_fields = ['input1...','input2...']; 假设数组的值是var rf_fields = ['input1...','input2...'];

  for(field in rf_fields){
    $('#form_wrapper').append( '<div class"form_question"></div>' );
    $('.form_question').append( '<div class"title"></div>' )    
                       .append( '<div class"question"></div>' )    
                       .append( $('<input>').attr( rf_fields[ field ]) )
                       .append( '<div class"eg"></div>' );
  }

The output I get is: 我得到的输出是:

<div id="form_wrapper">
  <div class"form_question"></div>
  <div class"form_question"></div>
</div>

The output I intend to get is: 我打算得到的输出是:

<div id="form_wrapper">

  <div class"form_question">
    <div class"title"> ... </div>
    <div class"question"> ... </div>
       --input--
    <div class"eg"> ... </div>
  </div>

  <div class"form_question">
    <div class"title"> ... </div>
    <div class"question"> ... </div>
       --input--
    <div class"eg"> ... </div>
  </div>

</div>

Can someone help me understand what I am doing wrong? 有人可以帮助我了解我在做什么错吗? Thanks! 谢谢!

Just put = at appropriate places, and the code will work. 只要将=放在适当的位置,代码就会起作用。

$('#form_wrapper').append( '<div class="form_question"></div>' );
$('.form_question').append( '<div class="title"></div>' )    
                   .append( '<div class="question"></div>' )    
                   .append( $('<input>').attr( rf_fields[ field ]) )
                   .append( '<div class="eg"></div>' );

You are missing the necessary = 's for attributes. 您缺少必要的=属性。 You also need to ensure you append to the newly created element, else it will fail after the first loop. 您还需要确保追加到新创建的元素,否则它将在第一个循环之后失败。

for(field in rf_fields){
    $('<div class="form_question"></div>')
        .append( '<div class="title"></div>' )    
        .append( '<div class="question"></div>' )    
        .append( $('<input>').attr( rf_fields[ field ]) )
        .append( '<div class="eg"></div>' )
        .appendTo($('#form_wrapper'));
}

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

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