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

How to use this variable to get the id of input in typeahead.js?

本文关键字:输入 id js typeahead 何使用 变量 获取      更新时间:2023-09-26

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

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

当 typeahead 在任何元素上处于活动状态时,我需要确定它的 id。这就是我正在尝试的。

$('.typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
},
{
    name: 'items',
    displayKey: 'value',
    source:populateItems()
});

var populateItems=function(){
    return function findMatches(inp, cb) {
    console.log("id: "+$(this).id);   //this is where i need to find the id
    jQuery.get("auto_suggestion.php",function(data){
        // some work here ..
        cb(res);
    });
  };
};

我试图在网上查看他们的例子和其他来源,但没有找到太多帮助。

不能从数据源函数访问元素。 this指向Dataset对象,并且没有对输入元素的引用。但是,您可以在循环中初始化 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).attr("id");

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