在select2中使用$(this)

Jor*_*ayo 3 jquery jquery-select2

我正在尝试从输入的html5数据属性中读取一个集合,该集合将转换为select2以创建标记.

当我有一个输入时,这是有效的:

$(".tags").select2(
  width: '220px'
  tags: $(".tags").data('collection')
)
Run Code Online (Sandbox Code Playgroud)

但我想使用元素本身的数据更安全地做到这一点,我试过这个:

$(".tags").select2(
  width: '220px'
  tags: $(this).data('collection')
)
Run Code Online (Sandbox Code Playgroud)

但它失败了,错误:

Uncaught query function not defined for Select2 investigador_aplicaciones
Run Code Online (Sandbox Code Playgroud)

你知道将元素本身与$(this)这样的特定选择器一起使用是否可行?

PSL*_*PSL 7

你可以这样做:

$(".tags").each(function(){
  var $this = $(this);
  $this.select2({
  width: '220px',
  tags: $this.data('collection')
  });
});
Run Code Online (Sandbox Code Playgroud)

因为在您的通话期间this不代表选择器中的元素.