使用JavaScript appendChild()为何仅输入框可见,嵌套按钮不显示
问题解决:动态添加字段时按钮不显示
核心问题是你把包含按钮的<span>元素嵌套进了<input>标签里,但<input>是自闭合的空元素,不能包含任何子元素,浏览器会自动忽略这种无效嵌套,导致按钮无法显示。
修正后的代码
var i = 1; function add_new_recipient() { var div_group = document.createElement("div"); div_group.setAttribute("class", "input-group"); var input = document.createElement("INPUT"); input.setAttribute("id", "txt_recipients" + i); input.setAttribute("Name", "txt_recipients" + i); input.setAttribute("type", "text"); input.setAttribute("class", "form-control required txt_recipients"); input.setAttribute("runat", "server"); var span = document.createElement("span"); span.setAttribute("class", "input-group-append"); var button_add = document.createElement("button"); button_add.setAttribute("id", "btn_add_new_recipients_field" + i); button_add.setAttribute("type", "button"); button_add.setAttribute("class", "btn btn-primary btn_add_new_recipients_field fa fa-plus"); button_add.onclick = function () { add_new_recipient(); } var button_remove = document.createElement("button"); button_remove.setAttribute("id", "btn_remove_new_recipients_field" + i); button_remove.setAttribute("type", "button"); button_remove.setAttribute("class", "btn btn-primary btn_remove_new_recipients_field fa fa-minus"); button_remove.onclick = function () { remove_recipient(div_group); } span.appendChild(button_add); span.appendChild(button_remove); // 关键修改:将input和span作为同级元素添加到div_group中,而非嵌套进input div_group.appendChild(input); div_group.appendChild(span); document.getElementById("new_recipient_input").appendChild(div_group); i++; } // 补充实现移除功能 function remove_recipient(container) { container.remove(); }
修改说明
- 调整DOM结构:把
<input>和包含按钮的<span>都作为input-group容器的直接子元素,符合Bootstrap input-group的布局规范。 - 完善移除功能:给移除按钮的点击事件传入当前的
div_group容器,确保能精准移除对应的字段组。
内容的提问来源于stack exchange,提问作者Ika
相关产品推荐
相关产品推荐

