如何在div标签中迭代输入标签并基于inputdata显示多个输入标签

时间:2019-07-01 11:22:15

标签: javascript html

我有“名称”字段,我想根据输入多次显示它。

赞:

名称:灰烬
名称:Win

var Property = [{
  "content": "Ash",
  "Name": "Name"
}, {
  "content": "Win",
  "Name": "Name"
}]
var data = Property;
for (var iter = 0; iter < data.length; iter++) {
  $("#Name").val(Property[iter].content);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div-id">
  <div class="form-row">
    <label for="Name"><i class="icon-tag"></i> Name </label>
    <input type="text" id="Name">
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

仅在循环内部创建输入元素并将其添加到HTML

var Property = [{
  "content": "Ash", "Name": "Name"
}, {
  "content": "Win", "Name": "Name"
}]
var data = Property;
var elem = "";
for (var iter = 0; iter < data.length; iter++) {
  elem += '<label for="Name"><i class="icon-tag"></i> Name </label><input type="text" id="Name" value="'+Property[iter].content+'"><br/>';
}
$("#inp").html(elem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "div-id">
  <div class="form-row">
    <div id="inp"> </div>
  </div>
</div>

答案 1 :(得分:0)

使用JQuery的append()将HTML元素添加到特定元素内,如下所示:

var Property = [{
  "content": "Ash", "Name": "Name"
}, {
  "content": "Win", "Name": "Name"
}]

Property.forEach(prop => {
  $("#form-row").append(`
  <label for="Name">
    <i class="icon-tag">${prop.Name}</i>
  </label>
  <input type="text" id="Name" value="${prop.content}"><br>
  `);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "div-id">
  <div id="form-row">
    
  </div>
</div>