JS+JQ原生类似双向数据绑定实现
// 原生双向数据绑定 <div class="row paddingLink"> <div class="col-md-4"> <label class="col-md-4"><span class="required">*</span>开户支行名称</label> <div class="col-md-8"> <input id="agentOpenAccName" class="form-control agentOpenAccName" autocomplete="off" placeholder="请输入或选择" onfocus="showAgentDiv(this)" oninput="filterAgentBank()" onblur="hiddenAgentDiv()"> <div id="dataAgentList" class="searchContent" onclick="pushAgentInput()" style="display:none;"></div> <article class="specialShow prompt">请输入开户支行名称</article> </div> </div> </div> let dataArr = [] function getopenAccName() { dataArr = [] let bankCode = $(".agentOpenBankName option:selected").val() let areaCode = $(".agentBankCounties option:selected").val() if(areaCode != "-1") { ajaxPromise({ data: { url: "/admin/posmer/posArea", requestType: "POST", expression: "branchName", areaCode: areaCode, bankCode: bankCode } }).then(res => { $.each(res, function(i,n) { $(".searchContent").append(`<p data="`+n.branch_no+`">`+n.branch_name+`</p>`) dataArr.push(n.branch_name) }); }).catch(err => { base.showMsg("服务异常", 1500) }) } } function showAgentDiv(x, node) { dataAgentList.style.display = "" $(x).removeClass("requiredIpt") $(x).siblings("article").addClass("specialShow") } function hiddenAgentDiv() { // 异步一下 setTimeout(() =>{ dataAgentList.style.display = "none" }, 200); } function filterAgentBank() { let e = event.target || event.srcElement let str = e.value dataAgentList.innerHTML = "" //清空div下的所有P元素 dataArr.forEach( (item) => { if (item.indexOf(str) != -1) { let p = document.createElement("p") let text = document.createTextNode(item) p.appendChild(text) dataAgentList.appendChild(p) } }) if (dataAgentList.innerHTML == "") { let p = document.createElement("p") let text = document.createTextNode("暂无数据") p.style.color = "#F5F5F5" p.onclick = () => { event.stopImmediatePropagation() } //阻止事件的冒泡 p.appendChild(text) dataAgentList.appendChild(p) } } // 搞一个双向绑定 function pushAgentInput() { //利用事件委托机制,获取点击的P源 let e = event.target || event.srcElement let input = document.getElementById("agentOpenAccName") input.value = e.innerText input.data = e.getAttribute("data") dataAgentList.style.display = "none" }