2013-02-05 62 views
1

我使用這個插件爲我自動完成表單: http://www.planbox.com/blog/news/updates/jquery-autocomplete-plugin-for-backbone-js.html檢查輸入值對數組

而不是檢查只有一個項目的,如下面的代碼(if (inputVal == 'bakaxel')), 我想檢查所選值對整個集合

var collection = new Backbone.Collection([ 
    {id:"AB", name:"Alberta"}, 
    {id:"AD", name:"Album"}, 
    {id:"BA", name:"barn"}, 
    {id:"BC", name:"bak"}, 
    {id:"BD", name:"baby"}, 
    {id:"BE", name:"band"}, 
    {id:"BF", name:"bakaxel"}, 
    {id:"BG", name:"batteri"}, 
    {id:"BH", name:"barbie"}, 
    {id:"MB", name:"Manitoba"}, 
    {id:"AP", name:"Armed Forces Pacific"} 
]); 

$('input.search').autocomplete({ 
    collection: collection, 
    attr: 'name', 
    noCase: true, 
    ul_class: 'search_options tr_list', 
    ul_css: {'z-index':1234} 
}); 

$('input.search').each(function(){ 
    $(this).blur(function(){ 
     var inputVal = $('input.search').val(); 

     if (inputVal == 'bakaxel') { 
      $('#search_result_page').load('searchResult.html'); 
      $('#searchPage').addClass('hidden'); 
     }  

    }); 
}); 

我想這一點,但我寧願不要再創建AR陣列,只需使用骨幹集合:

$('input.search').each(function(){ 

    $(this).blur(function(){ 
     var inputVal = $('input.search').val(); 
     var ar = ["Alberta", "Album", "barn", "bak", "baby", "band", "bakaxel", "batteri", "barbie", "Manitoba", "Armed Forces Pacific"]; 

     if (jQuery.inArray(inputVal, ar) != -1) { 
      $('#search_result_page').load('searchResult.html'); 
      $('#searchPage').addClass('hidden'); 
     } 

    }); 
}); 

回答

1

骨幹代理在您的情況下劃線功能和最明顯的是http://underscorejs.org/#where

其中_.where(列表屬性)
看起來通過列表中的每個值,返回所有的值的數組其中包含屬性中列出的所有 鍵值對。

您的測試可以寫成

var matches = collection.where({ 
    name: inputVal 
}); 
if (matches.length>0) { 
... 
} 

或者像@mu的意見建議,你可以只檢查輸入的存在與http://underscorejs.org/#find

var found = collection.find(function(model) { 
    return model.get('name') === inputVal 
}); 
if (found) { 
    ... 
} 
+1

如果你只是檢查是否存在,那麼['collection.find'](http://underscorejs.org/#find)可能更適合,但它在實踐中可能沒有多大區別。 –

+0

謝謝我會試試這個 – xxx12123