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');
        } 

    });
});
4

1 回答 1

1

骨干代理下划线功能,尤其是在您的情况下http://underscorejs.org/#where

where _.where(list, properties) 查看列表
中的每个值,返回包含属性中列出的所有键值对的所有值的数组。

你的测试可以写成

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) {
    ...
}
于 2013-02-05T14:23:41.253 回答