You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript在Bootstrap模态框指定位置创建HTML元素

当前代码使用document.body.appendChild将生成元素直接插入到页面body末尾,所以不符合插入位置要求,调整create函数插入逻辑即可,修改后的代码如下:

let a = 1;

// 创建带唯一id的文本输入框和日期选择器
function create() {
  // 定位到目标容器:modal-body下的container-fluid
  const modalContainer = document.querySelector('.modal-body .container-fluid');

  // 新建符合Bootstrap栅格规则的行元素
  const newRow = document.createElement('div');
  newRow.className = 'row';

  // 组装日期选择器模块
  const dateCol = document.createElement('div');
  dateCol.className = 'col-md-3 offset-md-1'; // offset-md-1用于对齐原有行的label占位宽度
  const pickdate = document.createElement("input");
  pickdate.type = 'date';
  pickdate.className = 'form-control input-lg';
  pickdate.id = "pickdate" + a;
  dateCol.appendChild(pickdate);

  // 组装文本输入框模块
  const textCol = document.createElement('div');
  textCol.className = 'col-md-7';
  const input = document.createElement("input");
  input.type = 'text';
  input.className = 'form-control input-lg';
  input.id = "txt" + a;
  textCol.appendChild(input);

  // 把组装好的列插入行,再把行插入目标容器末尾
  newRow.appendChild(dateCol);
  newRow.appendChild(textCol);
  modalContainer.appendChild(newRow);

  a++;
}

补充说明

  • 你可以根据实际布局需求调整col-md-*的数值,只要遵循Bootstrap栅格系统单行总宽度为12的规则即可
  • 如果需要在新增行前添加对应label,只需要额外创建一个col-md-1的列容器存放label,再对应调整后续列的宽度即可

内容的提问来源于stack exchange,提问作者chicken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:06:04