jquery - 在 select2 中使用 $(this)

标签 jquery jquery-select2

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

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

$(".tags").select2(
  width: '220px'
  tags: $(".tags").data('collection')
)

但我想使用元素本身的数据更安全,我尝试了以下方法:

$(".tags").select2(
  width: '220px'
  tags: $(this).data('collection')
)

但它失败并出现错误:

Uncaught query function not defined for Select2 investigador_aplicaciones

您知道是否可以将元素本身与 $(this) 等特定选择器一起使用?

最佳答案

您可以这样做:

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

因为在您的调用过程中,this 并不代表选择器中的元素。

关于jquery - 在 select2 中使用 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17436253/

相关文章:

javascript - $ 未定义,在 Rails 中使用 Select2 插件时未捕获 ReferenceError

javascript - Ajax 动态选择表单未提交值

javascript - Select2 不在 'append' 上运行

javascript - select2 中的默认选定选项使用远程数据进行多重选择

javascript - 数据表分页不起作用?

javascript - Select2 多选奇怪的叠加

php - 带有自动填充和添加新记录的 select2 下拉插件

javascript - jQuery Mobile 按钮未正确附加

javascript - jquery滚动问题

javascript - 如何将aspectRatio选项传递给jQuery UI的可调整大小函数中的alsoResize对象?