javascript - 无法使 Typeahead Bloodhound 工作

标签 javascript json

我是第一次使用 twitter typeahead.js。我首先从一个简单的本地数组开始,然后让它工作。

下一步,我现在尝试使其与 .json 文件一起使用。虽然我尝试了几种选择,但我无法使其工作,部分原因是我不太了解 Bloodhound 的工作原理。

HTML 代码

<div class="search_content">
  <input class="products" type="text" placeholder="products" value="">
</div>

JSON 文件(部分)

{
    "Products": [
        {   "name": "Pink Floyd",
            "Album": "The Best Of Pink Floyd: A Foot In The Door",
            "Label": "EMI UK",
            "Tracks":"Hey You, See Emily Play, The Happiest Days Of Our Lives, Another Brick in The Wall (Part 2), Have a cigar, Wish You Where Here, Time, The Great Gig in the Sky, Money, Comfortably Numb, High Hopes, Learning to Fly, The Fletcher Memorial Home, Shine On You Crazy Diamond, Brain Damage, Eclipse" ,
            "Price": "16.40",
            "Genre": "Rock"

        },
        {
            "name": "Depeche Mode",
            "Album": "A Question Of Time",
            "Label": "Mute",
            "Tracks":"A Question Of Time, Black Celebration, Something To Do, Stripped, More Than A Party, A Question Of Time(extended), Black Celebration" ,
            "Price": "4.68" ,
            "Genre": "Rock"
        }

    ]
}

Typeahead.js 代码

var products = new Bloodhound({
    datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.name); },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: '/js/products.json'

});

products.initialize();

$('.products').typeahead(null, {
    name: 'products',
    displayKey: 'name',
    source: products.ttAdapter()
});

最佳答案

您需要过滤响应,如下面的代码所示。 请在此处查看有关预输入用法的更多示例 https://twitter.github.io/typeahead.js/examples/

prefetch: {
  url: '/js/products.json',
  filter: function (products) {
            return $.map(products.Products, function (data) {
                return {
                    name: data.name
                };
            });
   }
}

关于javascript - 无法使 Typeahead Bloodhound 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21684931/

相关文章:

javascript - 不稳定的 jQuery 可拖动行为

javascript - 通过键名调用 JSON 对象的方法有何不同?

javascript - Node JS 从文件中加载 JSON 数组

javascript - 从每个文件中提取 JSON 对象并将其添加到数组中

c# - 如何拥有一个带有 json 动态成员的 WCF DataContract

javascript - 使用 JavaScript 获取多个选定的文本选项

javascript - ajax加载后显示内容

javascript - React js onClick无法将值传递给方法

python - 用于模拟响应的 Python Quick Rest API

javascript - 如何访问嵌套的 json 对象并使用 javascript 动态显示?