Javascript 如何使用此变量获取typeahead.js中输入的id?

Javascript 如何使用此变量获取typeahead.js中输入的id?,javascript,jquery,typeahead.js,Javascript,Jquery,Typeahead.js,我是第一次使用typeahead,这对我们很多人来说应该是一个简单的问题。我有多个输入元素,我正在使用typeahead。所有这些元素都具有相同的类 <input class="typeahead" type="text" id="element_1" > <input class="typeahead" type="text" id="element_2" > 我试图在网上看到他们的例子和其他来源,但没有找到太多帮助 试试 $(this).attr("id"); 。

我是第一次使用typeahead,这对我们很多人来说应该是一个简单的问题。我有多个输入元素,我正在使用typeahead。所有这些元素都具有相同的类

<input class="typeahead" type="text" id="element_1" >
<input class="typeahead" type="text" id="element_2" >
我试图在网上看到他们的例子和其他来源,但没有找到太多帮助

试试

$(this).attr("id");

。。。这使用jQuery,但使用我一直使用的快速、简单的方法获取Id属性。

您不能从数据源函数访问元素。这指向Dataset对象,并且并没有对输入元素的引用。但是,您可以在每个循环中初始化typeahead,以便访问当前输入元素:

$('.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指的是findMatches函数中的其他东西。它起作用了。谢谢好的,有一个新问题,如果我动态添加一些输入元素,语法应该是什么。
$('.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);
        // ...
    };
};