gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:22:10 26 4
gpt4 key购买 nike

我正在尝试为 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,然后创建一个新的 typeahead 函数手动添加源 person-search,以及另一个完全用于 .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'
});
});

关于javascript - 如何在 jQuery 的 ajax 函数中访问类中的元素 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11868253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com