Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何动态添加typeahead并获取输入元素的id?_Javascript_Jquery_Typeahead.js - Fatal编程技术网

Javascript 如何动态添加typeahead并获取输入元素的id?

Javascript 如何动态添加typeahead并获取输入元素的id?,javascript,jquery,typeahead.js,Javascript,Jquery,Typeahead.js,我使用typeahead.js时遇到了问题。我有这个html <input class="typeahead" type="text" id="element_1" > <input class="typeahead" type="text" id="element_2" > 如果有人可以帮助我,我应该如何使用它,以便也可以为动态创建的所有元素注册typeahead,同时我可以获取活动元素的id。您需要运行typeaheadeach()函数,作为对创建新输入的任何函数的

我使用typeahead.js时遇到了问题。我有这个html

<input class="typeahead" type="text" id="element_1" >
<input class="typeahead" type="text" id="element_2" >

如果有人可以帮助我,我应该如何使用它,以便也可以为动态创建的所有元素注册typeahead,同时我可以获取活动元素的id。

您需要运行typeahead
each()
函数,作为对创建新输入的任何函数的回调。理想情况下,将内部代码删除到新函数中,并从两个位置调用它。
$('.typeahead').each(function() {
    $(this).typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    }, {
        name: 'items',
        displayKey: 'value',
        source: populateItems(this.id)
    })
});


function populateItems (id) {
    return function findMatches(inp, cb) {
        console.log("id: " + id);  //this is where i am accessing id
    };
};