如何从 jQuery 中的 ajax 函数中的类访问元素 ID

How can I access the element ID from a class, within an ajax function in jQuery?

本文关键字:访问 元素 ID 函数 jQuery 中的 ajax      更新时间:2023-09-26

我正在尝试将预键入脚本用于引导程序。 它工作得很好,但我希望它更有活力。 我想在同一页面上运行多个自动完成输入,而无需重复代码。

.HTML:

<input type="text" class="typeahead" name="person_name" id="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search">

基本 jQuery:

$('.typeahead').typeahead({
    source: function(typeahead, query) {
        return $.ajax({
            url: '/ajax_lookup_script.php'
                + '?source=' + ###[HOW CAN I PUT ELEMENT ID HERE?]###
                + '&q=' + query,
            success: function(data) {
                return typeahead.process(data);
            }
        });
    },
    property: 'name'
});

以上是行不通的(显然)。 但是,如果我将类名设置为 .typeahead-person-search,然后创建一个手动添加源person-search的新 typeahead 函数,以及另一个完全用于.typeahead-city-search的函数,那么一切正常。 我想避免有两个函数,因为它实际上只是一个将两者分开的变量。

如何将活动.typeahead类的元素 ID 放入 $.ajax 函数中?

好的,我已经做了其他事情,我不能直接用 .typeahead 图书馆测试它,但我对另一个我有趣的图书馆做了同样的事情。

回合如何做

$('.typeahead').each(function(){
    var self = $(this);
    self.typeahead({
        source: function(typeahead, query) {
            return $.ajax({
                url: '/ajax_lookup_script.php'
                    + '?source=' + self.attr('id')
                    + '&q=' + query,
                 success: function(data) {
                    return typeahead.process(data);
                }
            });
        },
        property: 'name'
    });
});

编辑 :: 试试我的第二个答案它应该可以工作,我一直在另一个有相同问题的图书馆使用它

尝试类似的东西

var id = $(this).attr('id');

然后

var url = 'blahblah' + id + 'blablahblah);

并将 var URL 放在 ajax 查询中的 url: spot

您可以向包含网址动态部分的每个输入添加一个数据属性。

<input type="text" class="typeahead" name="person_name" id="person-search" data-source="person-search">
<input type="text" class="typeahead" name="city_name" id="city-search" data-source="city-search">

然后,您可以使用jQuery获取它并将其传递到URL中。

$('.typeahead').typeahead({
    source: function(typeahead, query) {
        var source = $(this).data('source');
        return $.ajax({
            url: '/ajax_lookup_directory/'+source+'.php?q=' + query,
            success: function(data) {
                return typeahead.process(data);
            }
        });
    },
    property: 'name'
});

您可以尝试以下操作

$('.typeahead').typeahead({
    source: function(typeahead, query) {
        return $.ajax({
            url: '/ajax_lookup_directory/' + $(this).attr('id') + '.php?q=' + query,
            success: function(data) {
                return typeahead.process(data);
            }
        });
    },
    property: 'name'
});