使用select2 4.0进行选择时触发回调,并检索上一次选择的值 [英] Fire callback when selection was made with select2 4.0, and retrieve the value of last selection

查看:1052
本文介绍了使用select2 4.0进行选择时触发回调,并检索上一次选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Select2(4.0)的最新版本,无法确定做出选择时如何触发事件,并无法检索上次选择的值(当使用可能进行多项选择的选择框时)

I am using the latest version of Select2 (4.0), and can't find out how to fire an event when a selection was made, AND retrieve the last selected value(when working with select boxes where multiple selections is possible).

在Select2的旧版本中,如果我没记错的话,做出选择时会触发插件所附加的选择的"onchange"事件,这暂时不起作用.

In older versions of Select2, if I remember correctly, the "onchange" event of the select to which the plugin was attached fired when a selection was made, this doesn't work at the momment.

我已经成功地触发一个javascript函数,当选择框选择的变化,但不能找出最后选定的ID呢.这是我的操作方式:

I've managed to fire a javascript function when the select boxes selection changes, but can't figure out the last selected id yet. Here's how I did it:

jQuery("#select2_holder").on("change", function(e) { 
        console.log(arguments);
});

我也尝试记录参数,但是我也无法在其中找到所需的信息.

I've also tried logging the arguments, but I can't find the desired information there either.

我已经阅读了官方网站上的文档,但是在其中找不到有关回调函数的任何信息.

I've read through the documentation on the official website, but I can't find anything about callback functions in it.

这里有人可以指出正确的方向吗?

Is there someone here who could point me in the right direction?

谢谢!

推荐答案

Select2提供了select2:select事件,该事件在每次选择新值时都会触发.对于单选,这等效于change,其中包含一些额外的元数据.

Select2 provides the select2:select event which is triggered any time a new value is selected. For a single select, this is equivalent to change with some extra metadata included.

您可以使用evt.data获取选定的数据对象,其中evt是传递给事件处理程序的第一个参数.

You can get the selected data object using evt.data where evt is the first argument passed into the event handler.

jQuery("#select2_holder").on("select2:select", function (evt) {
  console.log(evt.data);
});

您可以在Select2示例中找到事件的实时示例 .


You can find a live example of the events in the Select2 examples.

在Select2的较早版本中,如果我没有记错的话,做出选择时会触发插件所附加的选择的"onchange"事件,这暂时不会起作用.

In older versions of Select2, if I remember correctly, the "onchange" event of the select to which the plugin was attached fired when a selection was made, this doesn't work at the momment.

这是正确的,在Select2 3.x中,我们曾经修改了标准change事件并在其上添加了一些额外的属性.遗憾的是,由于这从来都不是一致的,并且当人们想要手动触发change时会引起问题,因此我们没有在Select2 4.0中修改标准的change事件.

This is correct, in Select2 3.x we used to modify the standard change event and put a few extra attributes on it. Since this was (unfortunately) never consistent, and it caused problems when people wanted to trigger change manually, we are not modifying the standard change event in Select2 4.0.

这篇关于使用select2 4.0进行选择时触发回调,并检索上一次选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆