首页 > 解决方案 > 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;
  }
})

如果您有任何解决方案,我将非常高兴!

非常感谢 !

标签: jquerythisjquery-ui-autocomplete

解决方案


您需要来自元素的实例特定数据的插件的一种常见方法是在each循环内启动插件

$(".autocomplete-file-label").each(function() {
  var category = $(this).attr("data-category");

  $(this).autocomplete({
      minLength: 3,
      source: function(request, response) {

        if (category == ''){
           ///.....
        }
      }
      //....
    }

  });
});

推荐阅读