jQuery 自动完成:如何获取 HTML 项目的 "id" 属性?

jQuery autocomplete: How to obtain HTML item's "id" attribute?

jQuery对我来说是新手,谢谢大家的包容

我在 HTML 中有一些文本输入:

<input type="text" class="NameTextID" id="fn.1">
<input type="text" class="NameTextID" id="ln.1">
<input type="text" class="EmailAddressTextID" id="ea.1">

两个输入是classNameTextID,一个是classEmailAddressTextID。注意每个 id 都是唯一的。

然后我想利用 jQuery 的自动完成功能对任何带有 class 的 DOM 项目 从上面。

$(document).ready(function() {
    $(function() {
        $( ".NameTextID" ).autocomplete({
            source: recEngineNames,
            minLength: recMinCharCount,
            select: recEngine
        });
        $( ".EmailAddressTextID" ).autocomplete({
            source: recEngineEmails,
            minLength: recMinCharCount,
            select: recEngine,
        });
    });
});

现在,在函数 recEngine 中:

var recEngine = function(event, ui) {
    var selected_value = ui.item.value
    var selected_id = ????
}

jQuery传了两个参数,激活的ui项如何获取id recEngine 函数?

提前致谢!

你可以这样做:-

var selected_id = this.id;

其中 this 指的是当前引用的元素。

您可以这样访问它: ui.item.id

首先,您可以通过用逗号分隔来使用多重选择器 ','

然后要获取触发事件的元素,您可以使用关键字 thisevent.target。 要获取其 ID,您可以使用 $(event.target).attr('id')

$(event.target).attr('id')

$(document).ready(function() {
    $(function() {
        $( ".NameTextID, .EmailAddressTextID" ).autocomplete({
            source: recEngineNames,
            minLength: recMinCharCount,
            select: recEngine
        });
    });
});

var recEngine = function(event, ui) {
    var selected_value = ui.item.value;
    var selected_id = $(event.target).attr('id');
}