使用typeahead.js从themoviedb中提取更多信息,并将其放入其他输入中

Extract more info from themoviedb using typeahead.js and put it in other inputs

本文关键字:输入 其他 js typeahead themoviedb 提取 使用 信息      更新时间:2023-09-26

我使用typeahead.js从moviedb api获取电影信息。当用户键入电影标题时,我需要获得电影的年份和电影的ID,以自动添加到其他输入中。

因此,当用户使用输入的电影标题并点击建议的标题时,它会自动将年份和电影id添加到其他输入

HTML代码

<input class="typeahead" placeholder="Movie Title Here"><br>
<input class="year" placeholder="Year Here">
<input class="id" placeholder="Year ID">

JS代码

靠近返回(在第12行),有我需要转移到其他输入的信息

var movies = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    remote: {
        url: 'http://api.themoviedb.org/3/search/movie?api_key=470fd2ec8853e25d2f8d86f685d2270e&query=%QUERY&search_type=ngram',
        filter: function (movies) {
            // Map the remote source JSON array to a JavaScript array
            return $.map(movies.results, function (movie) {
                    return {
                        id: movie.id,
                        value: movie.original_title,
                        year: (movie.release_date.substr(0,4) ? movie.release_date.substr(0,4) : '')
                    };
                });
            }
        }
    });
// Initialize the Bloodhound suggestion engine
movies.initialize();
// Instantiate the Typeahead UI
$('.typeahead').typeahead({
    hint: true,
    highlight: true
}, {
    displayKey: 'value',
    source: movies.ttAdapter(),
    templates: {
    empty: [
        '<div class="empty-message">',
        'unable to find any Best Picture winners that match the current query',
        '</div>'
    ].join(''n'),
    suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')
}
});

以下是我在jsfiddle上运行的代码,供您自己尝试:

http://jsfiddle.net/Jim_Toth/ss8L24x8/

我在这里添加了一种自动填充相关输入控件的方法:

http://jsfiddle.net/Fresh/cmq80qx3/

实现自动填充的代码的关键部分是:

bind("typeahead:selected", function (obj, datum, name) {
 $('.year').val(datum.year);
 $('.id').val(datum.id);
});

这段代码指定了在选择typeahead值时应该调用的函数,在这种情况下,它适当地设置了年份和id输入的值。