【问题标题】:Get the id from json file with twiiter typehead JQuery plugin使用 twitter typeahead JQuery 插件从 json 文件中获取 id
【发布时间】:2015-06-22 06:24:56
【问题描述】:

我有一个带有自动完成功能的简单文本框,我通过this plugin 设法实现了它。 一切正常,但是我想从 json 文件中检索与所选项目相关的 id,以便能够对数据库执行更新。

json 对象如下所示:

[{"id":1,"name":"John Smith"},{"id":2,"name":"Mary Brown"},{"id":3,"name":"Joe April"}]

Here's a working example 没有我想要弄清楚的 id 检索功能。

我知道我可以获取选定的名称并通过 json 对象循环执行新的搜索以匹配字符串并获取 id,但我想知道是否有更好的解决方案将名称和 id 作为数据集绑定在一起并轻松获取选定的 id,而无需在每次选择新名称时循环访问数据集。

【问题讨论】:

    标签: jquery html json twitter-bootstrap autocomplete


    【解决方案1】:

    试试

    $("#prefetch .typeahead").typeahead(null, {
      name: "customers",
      displayKey: "name",
      source: customers.ttAdapter()
    }).on("typeahead:selected", function(event, suggestion, data) {
      console.log(suggestion, suggestion.id);
    });
    

    参见jQuery#typeahead - Custom Events@

    typeahead:selected – 当下拉列表中的建议时触发 菜单被选中。事件处理程序将使用 3 个参数调用: jQuery 事件对象、建议对象,以及 建议所属的数据集。

    plnkr http://plnkr.co/edit/aK76DueDdivZMdhxwusA?p=preview

    【讨论】:

    • 好的,这部分可行,但确实指出了我正确的方向。这对我来说有点像魔术。 “数据”从何而来?我之所以问,是因为我必须在“选择”事件中检索 id,而不是在我键入时检索 id,否则它只会在键入时选择最后一个 id,而不是选择的那个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多