Javascript 在select2中获取当前元素

Javascript 在select2中获取当前元素,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我想通过使用一个类来使用multipleselect2,就像我在autocomplete中所做的那样,但是我在select2中没有做到这一点 这是我的密码: $('.select2-autocomplete').select2({ placeholder: "Search", minimumInputLength: 1, multiple: true, ajax: { url: "http://example.com/autocomplete-results",

我想通过使用一个类来使用multipleselect2,就像我在autocomplete中所做的那样,但是我在select2中没有做到这一点

这是我的密码:

$('.select2-autocomplete').select2({
  placeholder: "Search",
  minimumInputLength: 1,
  multiple: true,
  ajax: {
    url: "http://example.com/autocomplete-results",
    dataType: 'json',
    data: function(term, page) {
      return {
        q: term,
        type: $(this.element).data('type')
      };
    },
    results: function(data, page) {
      return {
        results: data
      };
    }
  },
});
除此之外,一切正常:

type : $(this.element).data('type') 
这里我需要select2元素的数据类型值,但它总是未定义的。你知道如何得到它吗

谢谢

编辑:



我想显示与ajax不同的结果,这就是我想通过ajax发送数据类型的原因。您可以在select2:open事件期间捕获活动元素,然后将其用于数据函数

以下是我的例子:

(function(){
var theSelect2Element = null;
$('.select2-autocomplete').select2({
   ...
   data: function(term, page) {
      return {
        q: term,
        type: $(theSelect2Element).data('type')
      };
   },
   ...
}).on('select2:open', function(e){ 
   theSelect2Element = e.currentTarget; 
}))();

祝你好运

您可以在select2:open事件期间捕获活动元素,然后将其用于数据函数

以下是我的例子:

(function(){
var theSelect2Element = null;
$('.select2-autocomplete').select2({
   ...
   data: function(term, page) {
      return {
        q: term,
        type: $(theSelect2Element).data('type')
      };
   },
   ...
}).on('select2:open', function(e){ 
   theSelect2Element = e.currentTarget; 
}))();
祝你好运

您可以使用
$(this.context)
,它将返回原始的select元素作为jQuery对象

data: function(term, page) {
  return {
    q: term,
    type: $(this.context).data('type')
  };
},
您可以使用
$(this.context)
,它将返回原始的select元素作为jQuery对象

data: function(term, page) {
  return {
    q: term,
    type: $(this.context).data('type')
  };
},

您需要动态设置数据类型有什么具体原因吗?是的,我的表单中有多个select2,服务器必须能够理解应该返回哪个结果,因此我想向服务器传递一个类型参数。演示会很有帮助。您的意思是我必须给出一个小提琴示例?您所说的类型是什么意思?像“字符串”或“数字”?还是输入的类型?文本字段等?元素是否具有“类型”属性?这有什么用?你需要动态设置数据类型有什么具体原因吗?是的,我的表单中有多个select2,服务器必须能够理解应该返回哪个结果,所以我想向服务器传递一个类型参数。演示会很有帮助。你的意思是我必须给出一个小提琴示例?你说的类型是什么意思?像“字符串”或“数字”?还是输入的类型?文本字段等?元素是否具有“类型”属性?这有什么用?