ES6 / Pure javascript / 无框架或jquery / Document.createElement()/ Node.appendChild() enter image description here
制作一个HTML表单,用户必须在其中添加成员详细信息。尝试创建一个按钮,以生成一个新的set op输入字段,该输入字段的className / id或占位符增加,例如:第一个生成的输入应具有className / id或input1的占位符,下一个带有className / id或input2的占位符,依此类推。
我已经创建了一个脚本,但是它会动态添加输入字段,但不会增加添加成员的计数。增量只能从1到10开始。
单击添加按钮时,必须添加输入字段,并且每次单击添加成员时计数都必须增加,最多只能有10个成员。
然后单击删除按钮,输入字段必须删除该成员 输入字段减少计数。
<div class="container ">
<form action="">
<input class="name" type="text" placeholder="Name">
<input class="email" type="email" placeholder="Email" value="abc@test.com">
<input class="phone" type="text" placeholder="Phone" value="8888888888">
<div class="field">
<div class="control">
<button class="button addMember">
Add Member
</button>
</div>
<div class="control">
<button class="button delMember">
Delete Member
</button>
</div>
<div class="control">
<button class="button resetForm">
Reset
</button>
</div>
</div>
</form>
</div>
<section class="addinputs">
</section>
</div>
<script>
document.querySelector(".addMember").addEventListener('click', getAdd);
function getAdd(event) {
event.preventDefault();
var count=1;
document.querySelector('.addinputs').innerHTML+=`
<div class="addedMember">
<input class="name ${count}" type="text" placeholder="Name ${count}">
<input class="email ${count}" type="email" placeholder="Email ${count}">
<input class="phone ${count}" type="text" placeholder="Phone ${count}">
</div>
`;
count++;
}
</script>
答案 0 :(得分:0)
编辑:已修复逻辑错误
这是您要找的吗?
document.querySelector(".addMember").addEventListener('click', getAdd);
document.querySelector(".delMember").addEventListener('click', getDel);
//Count as a global variable, not local
var count=0;
function getAdd(event) {
event.preventDefault();
//Set a limit on count
if(count <= 10) {
document.querySelector('.addinputs').innerHTML+=`
<div class="addedMember">
<input class="name ${count}" type="text" placeholder="Name ${count}">
<input class="email ${count}" type="email" placeholder="Email ${count}">
<input class="phone ${count}" type="text" placeholder="Phone ${count}">
</div>
`;
count++;
}
}
function getDel(event) {
event.preventDefault();
//Dont let count go below 0
if(count > 0) {
//Retrieve array of all added members
var added = document.getElementsByClassName("addedMember");
//Retrieve the last of all added members
var lastadded = added[added.length - 1];
//Remove the last added member from the DOM
lastadded.parentNode.removeChild(lastadded);
count--;
}
}