简体   繁体   English

达到select2 select的数据属性

[英]Reach data-attribute of select2 select

Is there a way to reach a data-attribute from within a select2? 是否有一种方法可以从select2内获取数据属性?

$('select').select2({
  ajax: {
    url: url + '&id=' + $(this).attr('data-id')
    //...
  }
});
//...
<select data-id="1"></select>
<select data-id="2"></select>
<select data-id="3"></select>

To pass a custom param to your ajax url in select2, you should use the data ajax function: 要将自定义参数传递给select2中的ajax URL,应使用data ajax函数:

$('select').select2({
  ajax: {
    url: "zee/base/url" // base url, no params
    data: function(params) {
      return {
        q: params.term,          // search term
        id: $(this).data('id')   // ta daaaa!
        page: params.page
      };
    },

    // moar ajax options
  },

  // moar select2 config options
})

As a general note, this inside select2 config options refers to the select2 instance (which is an object) and this inside the data function outlined above refers to the DOM element select2 was called upon, hence the jQuery wrapper $(this) has a .data() method. 作为一般注释, this内部SELECT2配置选项指SELECT2实例(其为对象)并且this内部data上面概述功能是指DOM元素SELECT2被召集,因此jQuery的包装$(this)有一个.data()方法。

Reading the document, it says that you can insert the url as a data-type in html select tag like so: 阅读文档时,它说您可以将url作为数据类型插入html select标签中,如下所示:

<select data-ajax--url="YOUR DESIRED URL" data-ajax--cache="true">
    ...
</select>

This url will override the options you have set inside of the function when calling, thus using a different one for each option you set it to in html. 调用时,此url将覆盖您在函数内部设置的选项,因此对于在html中设置的每个选项,将使用不同的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM