2017-08-24 63 views
0

我有一个复选框,并在一个HTML显示任何数量的文字和复选框在HTML

<div class ="followupSteps"> 
    <input type="checkbox" id="checkboxFollowup"> 
    <label for="checkboxFollowup" id="labelFollowup"></label> 
</div> 

根据输出的数量从服务器端返回的侧面的标签侧,可以有任意数量的复选框和标签。例如,如果从服务器返回5个输出,则会有5行(每行是1个复选框和1个标签)。我怎么做?

在jQuery中,我有$("#labelFollowup").text(somevar);但它不会创建一个新的行。相反,它会继续替换HTML中唯一定义的标签的内容。

+0

您需要向我们展示生成重复输入和标签的代码。 –

+0

你只需要遍历返回的数据,然后clone()和append()新行 –

回答

1

$(function(){ 
 
    let div = '<div class ="followupSteps">'+ 
 
    '<input type="checkbox" id="checkboxFollowup">'+ 
 
    '<label for="checkboxFollowup" id="labelFollowup">label</label>'+ 
 
    '</div>'; 
 
    for(var index=0; index<5; index++) 
 
    { 
 
     $('table').append('<tr> <td>'+div+' </td> </tr>') 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
<tr> 
 
</tr> 
 
</table>

试试这个。

0

var $followupDiv = $('.followupSteps'); 
 
var $inputClone = $('input', $followupDiv).clone().removeAttr('id'); 
 
var $labelClone = $('label', $followupDiv).clone().removeAttr('id'); 
 

 
var serverResponse = 5; 
 

 
for (i = 1; i <= serverResponse; i++) { 
 
    $inputClone.clone().attr('id', 'checkboxFollowup' + i).appendTo($followupDiv); 
 
    $labelClone.clone().attr('id', 'labelFollowup' + i).appendTo($followupDiv); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="followupSteps"> 
 
    <input type="checkbox" id="checkboxFollowup"> 
 
    <label for="checkboxFollowup" id="labelFollowup"></label> 
 
</div>

0

既然你没有提供太多的信息,我将只是张贴了如何使用一个javascript“为” 10次循环,并按照您的标记实现它:

for(i=0;i<10;i++) { 
     $('#checkboxFollowup').eq(0).clone().prop('id', 'clone'+i).appendTo('.followupSteps'); 
     $('#labelFollowup').eq(0).clone().prop('id', 'clone'+i).appendTo('.followupSteps'); 
    } 

使用下面的jQuery方法:

  1. https://api.jquery.com/eq/
  2. https://api.jquery.com/clone/
  3. http://api.jquery.com/appendto/
  4. http://api.jquery.com/prop/