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

时间:2012-08-08 15:44:14

标签: javascript jquery ajax autocomplete twitter-bootstrap

我正在尝试使用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-city-search,那么一切正常。我想避免使用两个函数,因为它实际上只是一个将两者分开的变量。

如何将有效.typeahead类的元素ID放入$.ajax函数?

4 个答案:

答案 0 :(得分:3)

好吧,我已经做了其他事情,我无法直接使用.typeahead librairy进行测试,但我对另一个我喜欢的图书馆做了同样的事情。

怎么回事

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

答案 1 :(得分:2)

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

尝试类似

的内容
var id = $(this).attr('id');

然后

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

并将var url放在url:spot

的ajax查询中

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

您可以尝试以下

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