h5 页面点击添加添加input框
h5 页面点击添加添加input框
前段时间有个需求,页面要能点击添加按钮控制input框的个数,当时感觉有点难,就没做,这两个又遇到了,没办法写了个简单的
效果图,加号增加,减号减少
直接上代码, 用来bootstrap的组件
div部分
<div class="container col-md-8" style="margin:100px"> <form id="mom" class="form-horizontal"> <div class="form-group"> <label class="col-sm-2 control-label">url</label> <div class="col-sm-10"> <input id="url" type="text" class="form-control" name="url"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">url1</label> <div class="col-sm-10"> <input id="url1" type="text" class="form-control" name="url1"> </div> </div> <div id="1" class="form-group"> <label class="col-sm-2 control-label"> 字段1 </label> <div class="col-sm-10"> <input type="text" id="key0" value=""> <input type="text" id="val0" value=""> <input id="add" type="button" value="+"> <input id="pop" type="button" value="-"> </div> </div> </form> <button id="send_mm" class="btn btn-default" style="margin-left:150px">Button</button> </div>
js 部分
<!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> var num = 0; var data1 = {}; $("input[id='add']").click(add); $("input[id='pop']").click(pop); $("button[id='send_mm']").click(send_urll); var momEle = document.getElementById("mom"); function add() { num++; console.log(num); var divEle = document.createElement("div"); divEle.setAttribute("class", "form-group"); divEle.setAttribute("id", `${num}`); var inner = `<label class="col-sm-2 control-label"> 字段 ${num} </label> <div class="col-sm-10"> <input type="text" value="" id="key${num}"> <input type="text" value="" id="val${num}" </div>`; divEle.innerHTML = inner; alert(divEle.innerHTML); momEle.appendChild(divEle); } function pop() { if (num != 0) { var current_dom = document.getElementById(`${num}`); momEle.removeChild(current_dom); num-- } else { alert('最少有一个字段') } } function send_urll() { for (i = 0; i <= num; i++) { var k = "key" + i; var v = "val" + i; var key = document.getElementById(`${k}`).value; var val = document.getElementById(`${v}`).value; // console.log(document.getElementById(`${k}`).value,document.getElementById(`${v}`).value); data1[key] = val } console.log(data1); var url = document.getElementById('url').value; var url1 = document.getElementById('url1').value; $.ajax({ url: "/get_url/", type: "POST", data: {"url": url, "url1": url1, "data1":JSON.stringify(data1)}, success: function (data) { alert(JSON.parse(data)); data1 = {} } }) } </script>
就是简单的dom操作,添加时增加div标签,难点在于每个input要有自己的key,当时还遇到一个坑
就是拼接的时候要用(`),不能用(')("), 这是es6的新语法
附上大佬博客的链接
https://www.cnblogs.com/liwenzhou/p/9249932.html#autoid-2-2-1