使用原生方式给select轮询生成多个option;
核心方法: 使用document.createDocumentFragment()文档碎片收纳多个options之后再一次性传递给指定dom
好处:
减少页面dom渲染次数:文档碎片收纳节点可一次性把动态生成的节点appendChild到指定节点上,而不是每生成一个节点都单独调用一次appendChild添加节点;
// 动态创建options
const Createdoptions = (domId, options) => {
// 先循环options插入到文档随便节点中,再文档碎片插入对应元素
const fragment = document.createDocumentFragment()
options.forEach((item, index) => {
// 取消默认选中,设置自己的类似 placeholder
if (index === 0) {
var option = document.createElement("option");
option.innerText = '--请选择--'
option.value = ''
option.setAttribute('disabled', true)
option.selected = true
fragment.appendChild(option)
}
var option = document.createElement("option");
option.innerText = item.label
option.value = item.value
fragment.appendChild(option)
})
$(domId).append(fragment)
}
实例:
// 职位插入选项options表标签
const JopOptions = [
{label: '老板', value: '老板'},
{label: '运营', value: '运营'},
{label: '财务', value: '财务'},
{label: '供应链', value: '供应链'},
]
Createdoptions('#select_jop', JopOptions)