【问题标题】:set data attributes with ajax and select2使用 ajax 和 select2 设置数据属性
【发布时间】:2017-01-23 17:21:21
【问题描述】:

我正在尝试将数据属性设置为 select2 选项但没有成功,此时我有以下 JS 代码

_properties.$localElement.select2({
    ajax: {
        url: "url",
        type: "POST",
        dataType: 'json',
        delay: 250,
        data: function (params) {
        return {
            name: params.term, // search term
            type: 1
        };
        },
        processResults: function (data) {

            return {
            results: $.map(data, function (item) {
                return {
                    text: item.name,
                    source: item.source,
                    id: item.id
                }
                })
            };
        },
        cache: true
    },
    //define min input length
    minimumInputLength: 3,

});

我想为选定的选项值设置一个数据源。

【问题讨论】:

  • 那么你的问题是什么?你有什么问题?
  • 以上没有尝试设置(或获取)任何data-* 属性。
  • 我尝试使用 resultTemplate 选项定义选项模板并在该输入上设置数据属性,但即使选择了正确的选项,该选项也没有设置自定义属性。
  • 请提供更多信息,我们可以提供帮助。
  • 我不明白这个问题的反对意见,我认为 OP 已经明确定义了他试图实现的目标和期望。这在我的情况下帮助了我,谢谢 Rubem。 +1

标签: javascript jquery-select2


【解决方案1】:

我找到了解决方案,看起来 resultTemplate 没有格式化“视觉”选择的选项,需要使用 templateSelection 选项:

    templateSelection: function(container) {
        $(container.element).attr("data-source", container.source);
        return container.text;
    }

【讨论】:

    【解决方案2】:

    您实际上可以使用您已经使用过的确切语法。 “source-attribute”只需要通过特定select2-option的data().data.source访问即可。

    所以保持你的 processResults 函数像你一样:

    processResults: function (data) {
       return {
          results: $.map(data, function (item) {
             return {
                text: item.name,
                source: item.source,
                id: item.id
             }
          })
       };
    },
    

    如果你想检索所选选项的来源,你可以这样做:

    var selectedSelect2OptionSource = $("#idOfTheSelect2 :selected").data().data.source;
    

    事实上,你可以在你的 processResults 函数中设置任何你想要的变量,然后通过 data().data.variableName 选择它!

    【讨论】:

      【解决方案3】:

      我解决了这个问题。

      $('select').on('select2:select', function (e) {
          var data = e.params.data;
          $("select option[value=" + data.id + "]").data('source', data.source);
          $("select").trigger('change');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-28
        • 2018-03-19
        • 1970-01-01
        • 1970-01-01
        • 2016-09-21
        • 2017-02-02
        • 2017-01-29
        • 1970-01-01
        相关资源
        最近更新 更多