//绑定下拉 function bindSelectOption(obj) { $('#' + obj + '_list li').click(function () { var obj_name = $(this).find('a').text(); var obj_id = $(this).data('id'); $('#' + obj + '_id').val(obj_id); $('#' + obj + '_name').val(obj_name); $('#' + obj + '_list').hide(); }); } //绑定搜索(延时搜索) function bindSearchOption(obj) { var last; $('#' + obj + '_name').keyup(function (event) { $this = $(this); if (obj != 'customer') { $('#' + obj + '_list li').hide().filter(":contains('" + ($(this).val()) + "')").show(); } else { last = event.timeStamp; setTimeout(function () { if (last - event.timeStamp == 0) { $('#customer_list').hide(); search_customer_name($this.val()); } }, 1000); } }); } function search_customer_name(customer_name) { if (customer_name == '') { return false; } var paramas = { 'customer_name': customer_name, } $.ajax({ type: "post", url: "/crm/Customer/searchName", data: paramas, dataType: 'json', success: function (result) { if (result.errorCode == 1) { popx(result.errorMsg, 5); } else { if (result.data.length > 0) { let liLine = `<li data-id="0"> <a href="javascript:void(0)">不限</a> </li>`; $.each(result.data, function (key, value) { liLine += `<li data-id='${value.id}'> <a href="javascript:void(0)">${value.name}</a> </li>` }); $('#customer_list').html(liLine).show(); bindSelectOption('customer'); } } }, }); }
html代码
<span class="select-box inline" style="margin-right:10px;">项目: <div class="btn-group" style="width:10%;"> <input class="dropdown-toggle form-control" data-toggle="dropdown" id="project_name" placeholder="项目" @if($project == '') value="不限" @elseif($project == 'yundou') value="芸豆会计" @elseif($project == 'xiaodou') value="小豆会计" @elseif($project == 'law') value="律师版" @endif readonly/> <input type="hidden" name='project' id='project' value='{{$project}}'/> <ul class="dropdown-menu" role="menu" id="project_list"> <li data-id=''><a href="javascript:void(0)">不限</a></li> <li data-id='yundou'><a href="javascript:void(0)">芸豆会计</a></li> <li data-id='xiaodou'><a href="javascript:void(0)">小豆会计</a></li> <li data-id='law'><a href="javascript:void(0)">律师版</a></li> </ul> </div> </span>
技术点说明:
1.延时搜索:
当输入框发生变化需要即时发送ajax调用api时,会严重浪费服务器资源。处理方案是输入完成几秒后再向服务端发送请求。
last = event.timeStamp; setTimeout(function () { if (last - event.timeStamp == 0) { //这里发送请求 } }, 1000);
2.下拉依赖bootstrap
元素中添加:
data-toggle="dropdown"
3.快速绑定下拉:
bindSelectOption('project');
4.快速绑定下拉搜索
bindSearchOption('project');