一 创建属性节点 createAttribute
1 首先创建一个select;
let inf = document.createElement('select');
2 创建一个事件
let sel= document.createAttribute('onchange');
3 给这个事件赋予一个方法名称
sel.value = "selChange()";
4 赋予
inf.setAttributeNode(sel)
二 针对js给 select 插入动态 option ,并支持模糊查询功能;
html代码
<div class="col-sm-6">
<div class="form-group" style="position:relative">
<label class="col-sm-3 control-label">微型站:</label>
<div class="col-sm-8 col-sm-offset-3" id="deptidPrent" style="position:absolute;top:5px;overflow:hidden;height:32px;">
</div>
<span class="col-sm-6" style="position:absolute;top:7px;height:30px;z-index:30">
<input type="text" name="ccdd" id="qlc_zdz" class="ccdd" placeholder="" style="width:100%;height:30px;border:none;text-indent: 10px;margin-left:2px;margin-top:1px;outline:0" onchange="inputSelect(this)"/>
</span>
</div>
</div>
ajax代码
function deptStart(){
let str = {};
str.condition = '3';
$.ajax({
url:"",
type:"",
data:str,
cache: false,
success:function(resp){
if(resp.code == '0'){
let inf = document.createElement('select'); //创建select节点
inf.id = "deptid"; //赋予id
inf.className = "form-control"; //赋予class
let arr = document.createAttribute("onchange"); //创建方法
arr.value="optChange()";
inf.setAttributeNode(arr);
let opt = '<option></option>'; //第一个为空,需求是select不是必选项
resp.data.forEach(item=>{
opt += `
<option value="${item.id}" data="${item.name}" onClick="optionClick(this)">${item.name}</option>
`;
})
inf.innerHTML = opt;
optAll = resp.data; //存储备用
document.getElementById('deptidPrent').appendChild(inf);
}
}
})
}
js 方法
功能1 点击select 下属option,拿到选中的option信息
function optChange(){
// 拿到value
let deptId = document.getElementById('deptid').value;
// 拿到name
let deptName = document.getElementById('deptid')[document.getElementById('deptid').selectedIndex].text
//将选中的 option 名称赋值给 input 搜索框
document.getElementById('qlc_zdz').value = deptName
}
功能2 input 模糊查询,更新select 下 option 列表
function inputSelect(e){
let optAll1 = optAll //拿到存储的原始option信息
let deptidPrent = document.getElementById('deptidPrent');
deptidPrent.innerHTML = ''; //将select清除,重新创建
let inf = document.createElement('select');
inf.id = "deptid";
inf.className = "form-control";
let arr = document.createAttribute("onchange");
arr.value="optChange()";
inf.setAttributeNode(arr);
let opt = '<option></option>';
for(let i=0; i<optAll1.length; i++){
if(optAll1[i].name.indexOf(e.value) !== -1){ // 进行模糊查询,等于 0 就是有该字段
opt += `
<option value="${optAll1[i].id}" data="${optAll1[i].name}" onClick="optionClick(this)">${optAll1[i].name}</option>
`;
}
}
inf.innerHTML = opt;
deptidPrent.appendChild(inf);
}
效果图