检查数组的输入值

时间:2013-02-05 13:40:42

标签: backbone.js input

我使用此插件作为自动填充表单: 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 个答案:

答案 0 :(得分:1)

Backbone代理Underscore功能,最值得注意的是http://underscorejs.org/#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) {
    ...
}