Javascript 如何动态添加typeahead并获取输入元素的id?
我使用typeahead.js时遇到了问题。我有这个htmlJavascript 如何动态添加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()函数,作为对创建新输入的任何函数的
<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
};
};