2

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

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,然后创建一个新的 typeahead 函数来手动添加 source person-search,以及另一个完全 for 的函数.typeahead-city-search,那么一切正常。当它实际上只是一个将两者分开的变量时,我想避免使用两个函数。

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

4

4 回答 4

3

好的,我已经做了其他事情,我无法直接使用 .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'
    });
});
于 2012-08-08T17:15:45.553 回答
2

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

尝试类似的东西

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

然后

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

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

于 2012-08-08T15:48:57.607 回答
0

您可以为每个包含 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'
});
于 2012-08-08T15:49:34.893 回答
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'
});
于 2012-08-08T15:49:56.927 回答