【问题标题】:Extract more info from themoviedb using typeahead.js and put it in other inputs使用 typeahead.js 从 themoviedb 提取更多信息并将其放入其他输入
【发布时间】:2014-12-07 12:14:57
【问题描述】:

我正在使用 typeahead.js 从 themoviedb 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/

【问题讨论】:

    标签: javascript jquery typeahead.js bootstrap-typeahead html-input


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 非常感谢,如果已经有这样的值jsfiddle.net/cmq80qx3/1,当用户点击输入时,它会自动打开建议列表(模拟向下箭头键),这样他就可以单击标题并获取其他输入的额外信息
    • 没问题。您应该为您在评论中提出的问题创建一个单独的问题,因为它与这个问题没有真正的关系。
    • 这非常有帮助!我一直在努力寻找如何做到这一点,并且文档没有给出任何像你的绑定那样的例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多