我不确定这是最好的方法,但是我正在尝试根据用户的需求动态创建表单的新部分。
这是我的HTML:
<div class="col-auto" id="nameEntries">
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text">Nom</div>
</div>
<input type="text" class="form-control" name="entrees[nom]">
</div>
</div>
<a href="#" onclick="addFields()">Ajouter une entrée d'argent</a>
我试图在用户按下链接时再次动态显示此部分。这是JS
function addFields() {
//creating the divs
var colDiv = document.createElement("div");
colDiv.class = "col-auto";
var inputGroupName = document.createElement("div");
inputGroupName.class = "input-group mb-2";
var inputGroupPrepend = document.createElement("div");
inputGroupPrepend.class = "input-group-prepend";
var inputGroupText = document.createElement("div");
inputGroupText.class = "input-group-text";
var nameNode = document.createTextNode("Name");
var nameInput = document.createElement("input");
nameInput.type = "text";
nameInput.class = "form-control";
nameInput.name = "entrees" + i + "[name]";
nameInput.placeholder = "...";
//appending them to each other
inputGroupText.appendChild(nameNode);
inputGroupPrepend.appendChild(inputGroupText);
inputGroupName.appendChild(inputGroupPrepend);
inputGroupName.appendChild(nameInput);
colDiv.appendChild(inputGroupName);
document.getElementById('nameEntries').appendChild(colDiv);
}
我添加了页面外观的图片。当用户按下“ Ajouter uneentréed'argent”时,与该字段相同的另一部分应出现在下方。
Link here
答案 0 :(得分:1)
function addFields() {
var wrapper = $('.wrapper');
// this is the HTML generated to append to the wrapper div. Don't use the id. You can use data-attributes to identify the columns. Or if you've something unique then you can use that as ID.
var outerDiv = $('<div/>').addClass('col-auto').append(
$('<div/>').addClass('input-group mb-2').append(
$('<div/>').addClass('input-group-prepend').append(
$('<div/>').addClass('input-group-text').html('Nom')
)
).append(
$('<input/>').attr({
'type': 'text',
'name': 'name'
}).addClass('form-control')
)
);
wrapper.append(outerDiv);
}
$(document).ready(function() {
$('#rowAdder').on('click', addFields);
addFields();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class=wrapper>
<!-- Your all the div elements will be added here. -->
</div>
<a href="#" id="rowAdder">Ajouter une entrée d'argent</a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</body>
</html>
答案 1 :(得分:0)
您可以使用cloneNode(true)
方法来复制现有的HTML结构:
xyz.appendChild(abc.cloneNode(true))
答案 2 :(得分:0)
var e = document.getElementById('child');
document.getElementById('parent').appendChild(e);