jquery - Jquery - 将 $(this) 传递给没有 var 的回调函数
问题描述
你好,精彩的社区!
我在 jquery 中有一个关于访问函数内部的 $(this) 的问题。通常我会使用 var 来传递它,但在实际情况下我无法定义任何 var。
而且我不知道如何通过“source:function()”的参数传递它。
我试过“来源:函数(请求,响应,self = $(this))”但它不起作用。
$(".autocomplete-file-label").autocomplete({
minLength: 3,
source: function(request, response){
var category = $(this).attr("data-category");
if(category == '')
{
var source = 'http://www.example.com/?term=' + request.term;
}
else
{
var source = 'http://www.example.com/?term=' + request.term + '&type=' + category;
}
$.ajax({
url: source,
data : request.term,
dataType: "json",
type: "POST",
success: function (data)
{
response($.map(data, function( item ) {
return item;
}));
}
});
},
focus: function( event, ui ) {
$(this).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$(this).val( ui.item.label);
$(this).next(".autocomplete-file-id").val( ui.item.id );
return false;
}
})
如果您有任何解决方案,我将非常高兴!
非常感谢 !
解决方案
您需要来自元素的实例特定数据的插件的一种常见方法是在each
循环内启动插件
$(".autocomplete-file-label").each(function() {
var category = $(this).attr("data-category");
$(this).autocomplete({
minLength: 3,
source: function(request, response) {
if (category == ''){
///.....
}
}
//....
}
});
});
推荐阅读
- axios - Axios post 根本不发送数据...设置 form-post 标头无法正常工作
- java - 从另一个线程实时更新 JLabel 文本
- javascript - 正则表达式在句末去掉句号,它应该保留句号
- java - Android Studio 处理多用户。如何修改布局的可点击参数?
- amazon-web-services - 是否可以编写一个在每周给定日期的不同时间运行的 cron 表达式?
- sql - 是否可以在 GraphQL 查询中创建计算或聚合列?
- r - R:当我在分隔列中有值 a、b、c 时,有没有办法获得 aa(bc) 表示法?
- python - collections.deque:为什么 q[9999] 比 q[-1] 快?
- javascript - 如何在正则表达式中强制执行总字符数?
- spring-boot - 获取整个父层次结构