繁体   English   中英

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

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

我正在尝试为Bootstrap使用typeahead脚本。 效果很好,但我希望它更具动态性。 我想在同一页面上运行多个自动完成输入,而无需重复代码。

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放在url:spot的ajax查询中

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

<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'
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM