【问题标题】:Autocomplete functionality to search through json object by attribute按属性搜索 json 对象的自动完成功能
【发布时间】:2016-03-05 09:55:48
【问题描述】:

假设我有以下 json 对象,其中包含一组人的信息。

data=[{id:2, fname:"bob", lname:"roberts", common_name:null, email:"sideshowbob@email.com", telephone:"555-555-5555", street:"333 Street St", city:"Salt Lake City", state:"UT", country:null, zip:"99999", dynamid:null, notes:null, director:false, contractor:false, contractor_need_agreement:false, shareholder:false, shares_held:0, company_id:1, created_at:"2016-02-23T10:15:09.339Z", updated_at:"2016-02-23T10:15:09.339Z", officer:false, snapshot:null, sign_term_voting:false, drag_liquidation_approval:false, rofr_consenter:false, investor_councel:false, ir_insured:false, issuer_signing_officer:false, issuer_registered_agent:false, issuer_councel:false, rep_lead_investor:false, rep_investor:false, rep_founder:false}, 
      {id:1, fname:"John", lname:"Smith", common_name:null, email:"john.smith@email.com", telephone:"555-555-5555", street:"333 Street St", city:"Salt Lake City", state:"UT", country:null, zip:"99999", dynamid:null, notes:null, director:false, contractor:false, contractor_need_agreement:false, shareholder:false, shares_held:0, company_id:1, created_at:"2016-02-23T10:15:09.327Z", updated_at:"2016-02-23T10:15:09.327Z", officer:false, snapshot:null, sign_term_voting:false, drag_liquidation_approval:false, rofr_consenter:false, investor_councel:false, ir_insured:false, issuer_signing_officer:false, issuer_registered_agent:false, issuer_councel:false, rep_lead_investor:false, rep_investor:false, rep_founder:false}]

现在我想在一个文本框中实现某种自动完成功能,该功能可以搜索每个人的姓名(即fname+" "+lname)以寻找匹配项。找到匹配项后,它会返回找到匹配项的人或该人的 id。

我在开始这方面遇到了一些麻烦。我想我可以用手写的方式写出来,我使用keyup 触发通过对象的循环,显示与字符串匹配的名称并在单击其中一个时返回相应的索引,但这似乎是我在重新发明轮子.

是否有一种有效/最佳实践方式来提取此类功能?

【问题讨论】:

  • 你可以试试 JqueryUI 自动完成功能...
  • 您可以将所有 fname+" "+lname 保存在一个数组中,并将其作为自动完成功能的来源

标签: javascript jquery json autocomplete


【解决方案1】:

来自这个 typeahead.js 演示 here:

jsfiddle上的完整代码:

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    matches = [];

    substrRegex = new RegExp(q, 'i');

    $.each(strs, function(i, str) {
      var fullname = str.fname + " " + str.lname
            console.log(fullname);

      if (substrRegex.test(fullname)) {
        matches.push(fullname);
      }
    });

    cb(matches);
  };
};

【讨论】:

  • 嘿,感谢您的回复和小提琴。当我选择值(即来自对象的 id)时,我会对最终从自动完成中获取其他属性感兴趣。我该怎么做?
  • 我不确定我是否理解你,你能举个例子吗
  • 如果要获取被选人的id:jsfiddle.net/refan/a62vuceu/4
  • 您好,感谢您的更新。抱歉我没有早点回复。当我得到一个秒时,我会仔细看看这个,但它看起来像我所追求的。一旦我尝试过,我一定会相信你的答案。
  • 你最新的小提琴正是我想要的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2012-06-16
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
相关资源
最近更新 更多