【问题标题】:How to get data attribute of <select> for use in select2 from inside .select2() ajax call?如何从 .select2() ajax 调用中获取 <select> 的数据属性以在 select2 中使用?
【发布时间】:2015-08-28 06:02:30
【问题描述】:

我需要知道我的 select2 UI 基于什么元素,以便我可以从数据属性中获取数据。也许我在文档中遗漏了它,但我似乎无法弄清楚如何获得它。

以下是我的代码设置的基础知识:

<form>
  <!--SNIP-->
  <select class="select-records" data-index=0>
    <option>Choose some records</option>
  </select>
  <!--SNIP-->
</form>

<script>
  $('.select-records').select2({
    ajax: {
      url: "/ajax/records",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        // Need to get the data-index of the base <select> to process/pass along more info here
        return {
          q: params.term,
          page: params.page
        }
      },
      processResults: function(data, page) {
        return {
          results: data.items
        }
      },
      cache: true
    },
    minimumInputLength: 3
  });
</script>

如您所见,我需要访问定义要随 ajax 请求发送的参数的函数内部的数据属性(或 id)。

【问题讨论】:

  • 愿意分享您的代码和尝试吗?
  • 我还没有尝试过任何东西,因为我找不到任何可以告诉我尝试什么的东西。代码真的很基础,至少在与获取信息直接相关的方面。这是一个要点:gist.github.com/Gremlyn/75cdd1a3aa6457efe477

标签: jquery-select2


【解决方案1】:

假设您想为您的选择元素添加到您的 ajax 查询...&ui=select1。

  1. 按以下方式定义您的选择:&lt;select data-ajax--id='select1' class="select-records" data-index=0&gt;

  2. 你的 ajax 的数据函数现在应该是:

    函数(参数){ 返回 { q:params.term, ui: this.id, 页面:params.page } }

【讨论】:

  • 谢谢,这听起来应该可以解决问题。明天我会尝试一下,一旦我确认就选择你的答案。我对文档的阅读表明这仅适用于现有的 select2 选项,而不是我可以即时弥补的选项。
  • 请注意,4.0.1 中会有一个重大更改(错误修复),它将更改 this 以引用当前元素。这是 GitHub 上的 ticket 3361
  • @KevinBrown - 所以如果我没看错,this 将引用 UI 所基于的 &lt;select&gt;,而不是 ajax 对象?如果是这样,我可以直接访问我添加到 &lt;select&gt; 的数据属性,这是我最初尝试做的。
  • @TheGremlyn 正确,这将在 4.0.1 中被允许。现在,在使用 4.0.0 时,您将不得不接受这样的 hack。
  • 希望我能投票更多。这拯救了我的一天。我把头发扯掉了!谢谢!
猜你喜欢
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2020-08-29
  • 2018-01-31
相关资源
最近更新 更多