实现一个页面需求,需要点击按钮增加一组元素,通过参考Blog 完成功能
并且提供删除元素的一组元素的按钮功能
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> HTML5 page 1 网页设计</title>
</head>
<script type="text/javascript">
var count = 1;
//用来判断是删除 还是增加按钮 以便count值进行计算
function checkCount(boolOK, coun) {
if (boolOK == true) {
return count++;
}
else {
count--;
}
}
//添加一个input标签 同时也对它的ID和Name进行赋值。
function AddInput() {
countAA = checkCount(true, count);
var question = document.getElementById("question");
//创建input
var input = document.createElement("input");
input.type = "text";
input.id = "questions[" + count + "]_text";
input.name = "questions[" + count + "].name";
question.appendChild(input); //向元素增加子节点 最为最后一个子节点
var input = document.createElement("input");
input.type = "button";
input.id = "questions[" + count + "]_btn";
input.name = "questions[" + count + "].name";
input.value="按钮";
question.appendChild(input);
//创建一个空格
var br = document.createElement("br");
br.id ="questions[" + count + "]_br"
question.appendChild(br);
}
function DealInput(){
//删除最后添加的一组元素:button text br
var inputdel = document.getElementById("questions[" + count + "]_text");
question.removeChild(inputdel)
var inputde2 = document.getElementById("questions[" + count + "]_btn");
question.removeChild(inputde2)
var inputde3 = document.getElementById("questions[" + count + "]_br");
question.removeChild(inputde3)
countAA = checkCount(false, count);
}
</script>
<body ">
<div style="width: 500px; margin-left: 200px;">
<div id="question" style="border: 1px solid yellow;">
<input id="Text1" type="text" />
<input id="btnAddInput" type="button" value="新增一个Input" onclick="AddInput()" />
<input id="btnDealInput" type="button" value=" 删除元素" onclick=" DealInput()">
<br />
</div>
</div>
</body>
</html>
运行逻辑
1、增加按钮组
1.1 获取一个新的按钮id号
1.2 对div-question 增加一组子节点元素,按钮,文本 还有换行符
2、删除按钮组
2.1 通过.getElementById()函数 来获取html元素,获取最后一组元素ID
2.2 删除 一组子节点元素,按钮,文本 还有换行符
效果截图
1、页面初始状态
2、点击按钮来增加元素
3、点击按钮删除元素
参考内容
javascript点击按钮,增加文本框和按钮
https://blog.csdn.net/tt010175/article/details/78193357