如何使用 Materialize 获取元素属性 onAutocomplete

How to get element attributes onAutocomplete with Materialize

我在 3 个输入元素上使用相同的 Materialise 自动完成功能。然后在 onAutocomplete() 上,我需要获取使用自动完成功能的元素的 ID,以便我可以在正确的位置填充数据。所以我想知道它是 autocomplete-input1 还是 autocomplete-input2。我怎样才能在纯 javascript 中做到这一点?

<div class="col s12">
    <div class="row">
        <div class="input-field col s6">
            <input type="text" id="autocomplete-input1" class="autocomplete" autocomplete="off">
            <label for="autocomplete-input1">Input1: Type my name - Radek</label>
        </div>            
        <div class="input-field col s6">
            <input type="text" id="autocomplete-input2" class="autocomplete" autocomplete="off">
            <label for="autocomplete-input2">Input2: Type my name - Radek</label>
        </div>
    </div>
</div>

我想知道用户输入的元素的 ID 并使用自动完成功能。 javascript 代码将成为 onAutocomplete 函数的一部分。我尝试了几个选项,但 none 有效。

$(function () {
    $('input.autocomplete').autocomplete({
        data: {
            "Radek Surname &lt;br&gt;&nbsp;&nbsp;radeksurname@ymail.com": null,
            "Radek": null,
            "Radoslav": 'http://placehold.it/250x250'
        },
        onAutocomplete: function(txt) {
          console.log(this.getAttribute("id"));
          console.log(this.id);
          console.log(this.innerHTML);
          console.log(this.innerText);
          console.log(this.outerHTML);
        },
        limit: 20, 
    });

});

您可以在 ..

左右使用此 jsFiddle 和 fiddle

示例 1 - JsFiddle

$(function () {
    const selector = 'input.autocomplete';
    let currentActiveAutoCompleteInput = null;
    document.querySelectorAll(selector).forEach(el => {
        el.onchange = function(evt) {
            currentActiveAutoCompleteInput = evt.target;
        };
    });
    $(selector).autocomplete({
        data: {
            "Radek Surname &lt;br&gt;&nbsp;&nbsp;radeksurname@ymail.com": null,
            "Radek": null,
            "Radoslav": 'http://placehold.it/250x250'
        },
        onAutocomplete: function(txt) {
            console.log(currentActiveAutoCompleteInput.id);
        },
        limit: 20, 
    });
});

示例 2 - JsFiddle

$(function () {
    let currentActiveAutoCompleteInput = null;
    $('input.autocomplete')
    .on('change', function(evt) {
        currentActiveAutoCompleteInput = evt.target;
    })
    .autocomplete({
        data: {
            "Radek Surname &lt;br&gt;&nbsp;&nbsp;radeksurname@ymail.com": null,
            "Radek": null,
            "Radoslav": 'http://placehold.it/250x250'
        },
        onAutocomplete: function(txt) {
          console.log(currentActiveAutoCompleteInput.id);
        },
        limit: 20, 
    });
});