jQuery select2控件 - 检索最后选择的元素 [英] jQuery select2 control - retrieve last selected element

查看:156
本文介绍了jQuery select2控件 - 检索最后选择的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery select2控件,我需要实现以下功能:如果用户尝试添加某个元素,基于某种算法,我应该从选择中删除另一个(不兼容的)元素。我看到了两种实现方法:

I am using jQuery select2 control and I need to implement the following functionality: if the user tries to add a certain element, based on some algorithm, I should delete another (incompatible) element from the selection. I see two ways to achieve that:

1)禁止自动排序所选值
2)获取最后一个选定项的值并选择性地删除不兼容的项从列表中

1) inhibit automatic sorting of selected values 2) get value of the last selected item and optionally remove the incompatible item from the list

对于1)我无法想象如何禁止自动排序(在执行选择后,数据和值都被排序)
2)我无法在任何地方找到最后选择的项目信息(我希望在选择事件 e 变量中找到一些内容。)

For 1) I could not figure how to inhibit auto sorting (both "data" and "values" are ordered after a selection is performed) For 2) I could not find last selected item information anywhere (I expected to find something in the select event e variable).

My代码如下:

    $("#PhaseFilterSelectedList").select2()
       .on("select2:select", function (e) {
           // removing option inconsistent with last selected item, if any
           var allData = $("#PhaseFilterSelectedList").select2("val");
           if (!allData || allData.length < 2)
               return;

           //alert("Value = " + $("#PhaseFilterSelectedList").select2("val").join(','));
           //alert("Data = " + $("#PhaseFilterSelectedList").select2("data")[0].id + " " + $("#PhaseFilterSelectedList").select2("data")[1].id);

           var lastItemId = allData.slice(-1)[0];
           var lastItemHalf = Math.floor((parseInt(lastItemId) + 1) / 2);
           var toRemove = jQuery.grep(allData, function (elem, index) {
               return elem != lastItemId && Math.floor((parseInt(elem) + 1) / 2) == lastItemHalf;
           });

           if (!toRemove || toRemove.length < 1)
               return;

           allData.splice($.inArray(toRemove[0], allData), 1);
           $("#PhaseFilterSelectedList").select2("val", allData);

       })

不兼容的元素删除工作正常,但我遇到了麻烦识别用户执行的最后一次选择。

Incompatible element removal works fine, but I have trouble with identifying the last selection performed by the user.

任何想法如何执行此任务?谢谢。

Any idea how can I perform this task? Thank you.

推荐答案

第二部分可能会对你有所帮助:

for the second part this may help you:

$(this).val(); // references the select

你可以过滤它以获得所有需要的值。

you can filter it to get all needed values.

一个例子就是小提琴: http://jsfiddle.net/jEADR/ 1588 /

A Example is in the fiddle: http://jsfiddle.net/jEADR/1588/

这篇关于jQuery select2控件 - 检索最后选择的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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