jquery實現帶搜索的下拉框

jquery實現帶搜索的下拉框

小白菜就不多說了,因爲知之甚少。
這裏寫圖片描述
這是hmtl的樣式

* {margin:0;padding:0;}
.dropdown {display:inline-block;width:200px;height:28px;border:1px solid #808080;position:relative;}
.dropdown .editor {display:block;border:0;padding:0;width:100%;box-shadow: inset 1px 2px 3px #ddd;height:inherit;}
.dropdown .trigger {position:absolute;top:0;right:0;}
.dropdown ul {display:none;width:100%;z-index:1111;height:140px;padding:2px;position:absolute;top:100%;background-color:#FFF;border:1px solid #DDD;border-radius: 0 0 5px 5px;overflow-y:auto;overflow-x:hidden;}
.dropdown ul li {height:20px;display:block;font-size:12px;overflow:hidden;cursor:pointer;}
.dropdown ul li .hot {color: red;}
.dropdown ul li:hover {background-color: #EEE;}
.dropdown ul .search {display:block;backgound: url(imgs/search.gif) no-repeat scroll center right;border-bottom: 1px solid #808080;}
.dropdown ul .search:hover{background-color:#FFF;}
.dropdown ul .search input {padding:2px;width:100%;border:0;font-size:14px;background:none;}

<tr style="height:25px;">
        <th>國家/地區</th>
        <td>
        <div  class="dropdown" >  <!-- 模擬 select 的標記, -->
        <input class="editor"   id="birthplace" data-bind="birthplace"  oninput="" onpropertychange="" data-role="inoutcombobox"
         data-name="birthplace" name="birthplace" type="text"   readonly="readonly"  
         data-read-url="/GcCombox/resume/getCountryList" required validationMessage='請填寫國家!' /> <!-- 顯示當前值的輸入框 -->
        <ul>   <!-- 列表菜單 -->
            <li class="search"><input type="text" style="height:38px;padding-bottom: 18px;" placeholder="輸入查詢" /></li>   <!-- 過濾輸入的列表, -->
            <!-- 添加數據的時候,都添加在這個地方 -->
        </ul>
        </div>
        </td>
    </tr>

上面的οninput=”“和onpropertychange=”“這個是關鍵,因爲我的主要思路是在下拉列表中選擇item之後,強制調用input的oninput方法,onpropertychange是爲了在ie下也可以用( 我測試的是ie8)。上面的是html。


(function(){  
        //當列表項被點擊時,把列表項的值放在輸入框裏面,
(“.dropdown”).delegate(“li”, “click”, function(e){
var v = (this).attr(dataname),drop= (this).closest(“.dropdown”);

        var kv = $(this).attr("value");

        if(kv == null || kv == ""){
            kv ="null";
        }
        var msgDiv = $(this).parent().parent().find("input").eq(0).attr("name");
        drops = $("[name='"+msgDiv+"']");
        drops.attr("value", kv);
        drops.attr("data-value", kv);
        //這裏強制調用input的oninput,onpropertychange方法
        $("[name='"+msgDiv+"']").trigger('oninput');
        $("[name='"+msgDiv+"']").trigger('onpropertychange');
        drop.attr("value", kv);
        drop.attr("data-name", v);
        drop.find(".editor").val(v);
        $(this).parent().hide();
        e.stopPropagation();
    }).delegate(".editor", "click", function(e){    //當下拉按鈕被點擊時,顯示數據列表
        $(this).closest(".dropdown").find("ul").show();
        e.stopPropagation();  //阻止冒泡,因爲冒泡到 document 的時候,會隱藏列表
    }).delegate(".search input", "click", function(e){
        e.stopPropagation(); 
    }).delegate(".search input", "keyup", function(e){    //當檢測到列表中的輸入框的時候,啓動過濾,不滿足的項隱藏
        var v = $.trim(this.value), list = $(this).closest("ul").children("li");
        if(v == "") {    //特殊情況,過濾輸入框中沒有值的時候迭代所有的列表項並顯示它們
            list.each(function(){
                if(this.className.indexOf("search") != -1) {return;}//不考慮過濾輸入框所在的列表項
                $(this).text(this.innerText || this.textContent).show();
            });
        } else {
            list.each(function(){   //迭代列表,
                if(this.className.indexOf("search") != -1) {return;}  //不考慮過濾輸入框所在的列表項
                var lv = $(this).text();   //列表的文本
                if(lv.indexOf(v) === -1) {   //不匹配過濾文本,就隱藏
                    $(this).hide();
                } else {                 //匹配,把匹配的文本替換會含有標記的文本(紅色)
                    $(this).html(lv.replace(v, '<span class="hot">'+v+'</span>')).show();
                }
            });
        }
    });
    $(this).click(function(){ 
        //當數據列表在顯示時,如果點擊了頁面其它區域,則隱藏列表
        $(".dropdown ul:visible").hide();   
    });
    $(".editor").click(function (e){ 
        var url = e.target.getAttribute("data-read-url");
         $.ajax({  
             url: url,  
             type: 'GET',  
             dataType: 'json',  
             timeout: 1000,  
             cache: false,  
             beforeSend: LoadFunction, //加載執行方法    
             error: erryFunction,  //錯誤執行方法    
             success: succFunction //成功執行方法    
         })  
         function LoadFunction() {  
             $("#list").html('加載中...');  
         }  
         function erryFunction() {  
             alert("error");  
         }  
         function succFunction(tt) {  
             $("#list").html('');  
             var json = eval(tt); 
             var p = $(".dropdown ul");
             $('ul>#contentdrop').remove();
             var fragment = document.createDocumentFragment(), li;//數組   
             $.each(json, function (index, item) {  
                 //循環獲取數據    
                 var itemKey = json[index].itemKey;  
                 var itemName = json[index].itemName;  
                    li = document.createElement("li");
                    li.setAttribute("value", itemKey);
                    li.setAttribute("data-name", itemName);
                    li.setAttribute("id", "contentdrop");
                    li.innerHTML = itemName;
                    fragment.appendChild(li);
             });
             p.append(fragment);
         }  
    });
});

input的oninput,onpropertychange方法我寫在全局的js中
var elVal;
$(“[data-bind=’birthplace’]”).bind(‘oninput onpropertychange’, function(e) {
if (role == ‘datepicker’) {
                        elVal =    $(e.currentTarget).datepicker("getDate");
                            that.inputForm.formData[paramName] = elVal;
                        }else{
                            //下面兩行就是把改變後的值賦值給form表單用於保存
                            elVal = $(e.target)[0].getAttribute("value");
                            that.inputForm.formData[paramName] = elVal;
                            var onchange = el.data("onchange")
                            if (onchange) {
                                that.inputForm[onchange](e);
                            }
                        }
                        if (elVal) {
                            var msgDiv = el.closest("td").find("div").eq(1);
                            msgDiv.remove();
                        }
                    });

基本思路就是
1.在 select點擊的時候給input attr 加屬性和值
2.然後trigger調用oninput,onpropertychange方法(注意,我是必須在我的html的input中加入 οninput=”” onpropertychange=”“),如果沒加就調用不到.bind(‘oninput onpropertychange’, function(e)這個方法。
3.在bind(‘oninput onpropertychange’, function(e)這個方法中改變form的值。
4.在頁面的初始化的時候我重新調用url取得value和key的對應值 因爲我保存的是編碼
if(role==’inoutcombobox’){
var k = value;
var url = el.data(“read-url”);
if (url) {
$.get(url,function(res){
if (res) {
for( var m in res) {
//console.log(res[m].itemKey);
if(res[m].itemKey == k){
el.val(res[m].itemName);
}
//遍歷對象,k即爲key,obj[k]爲當前k對應的值
}
}
});
}
}
5.以上是大致思路,每個人的框架代碼不同,最終解決方案很難從網上找到匹配度高的,給個思路和方法自己嘗試。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章