如何在HTML元素后添加换行 解决JS动态生成输入框布局异常问题
问题描述
实现点击按钮新增输入框的功能,目标是每生成一个div后插入换行,保证输入框组布局正常。
原有div间距正常,但点击add_more按钮后生成的输入框布局不符合预期。
期望生成的结构
<div> Key Term 2: <input id="el2" type="text" value=""> <br> </div> <br>
现有实现代码
JS逻辑
function add_more() { // we've added more inputs. addMore = true; // set html generated to false, because new inputs have been added. htmlGenerated = false; // increment the number of inputs. numberOfInputs++; //fetch the input boxes. inputs = document.getElementById("inputBoxes"); // create newline br_key = document.createElement("br"); // create newline br_description = document.createElement("br"); //create a new row for a key term. row = document.createElement("div"); // set the key term text. row.innerHTML = "Key Term "; row.innerHTML += numberOfInputs; row.innerHTML += " :"; // create the input for the key. key = document.createElement("input"); key.setAttribute("id", "el" + numberOfInputs); //add the key to the row. row.appendChild(key); row.after(br_key); //create a row for the new description. row2 = document.createElement("div"); // set the description text. row2.innerHTML = "Description " row2.innerHTML += numberOfInputs; row2.innerHTML += " :"; // create the description input description = document.createElement("input"); description.setAttribute("id", "dl" + numberOfInputs); // add the description to the row. row2.appendChild(description); row2.after(br_description); // add the rows for the key and the description to the inputBoxes. inputs.appendChild(row); inputs.appendChild(row2); }
实际生成的HTML结构
<div>Key Term 5 :<input id="el5"></div>
可尝试的解决方案
- 调整br元素的插入时机:当前是在row、row2还未挂载到父容器时调用
after插入br,此时元素不在DOM树中,插入操作不会生效。删除原有row.after(br_key)、row2.after(br_description)两行,把br直接追加到父容器即可,修改逻辑如下:
// 替换原有追加row、row2的代码 inputs.appendChild(row); inputs.appendChild(br_key); inputs.appendChild(row2); inputs.appendChild(br_description);
- 如果需要input标签后也插入换行,直接把br追加到row、row2的内部,示例:
// 在row.appendChild(key)之后添加 row.appendChild(br_key); // 在row2.appendChild(description)之后添加 row2.appendChild(br_description);
- 改用CSS控制间距替代br元素,维护性更高:给新增的div元素设置margin-bottom属性控制上下间距,示例:
row.style.marginBottom = '8px'; row2.style.marginBottom = '16px';
内容的提问来源于stack exchange,提问作者Evan Gertis
相关产品推荐
相关产品推荐

