作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试为 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/
我是一名优秀的程序员,十分优秀!