Select2 从多个中获取删除的值

Select2 obtaining removed value from multiple

我使用的主题是 select2 版本 3.4.3。我想获取删除的值 ID,所以我尝试了:

$('#mymultiple').on("select2:removed", function (e) {
    console.log(e.val);
})

但它没有检测到该事件。然后,我测试了:

$('#mymultiple').on("select2:unselect", function (e) {
    console.log(e.val);
})

但是它给了我一个未定义的值,尽管对象有一些信息:

$('#mymultiple').on("select2:unselect", function (e) {
    console.log(e);
})

Object { type: "select2:unselect", params: Object, timeStamp: 1473273802173, jQuery18308796073916839738: true, isTrigger: true, exclusive: undefined, namespace: "", namespace_re: null, result: undefined, target: , ...}

我必须使用这个版本,因为我需要使用模板项目给定的样式(我测试了3.5.3,removed可以正常工作,但我无法正确导入样式)。那么如何从多个 select?

中获取删除的值

似乎 select2 ver 3.4.3 不支持删除元素事件。

您可以改用此解决方法:

note that my code support removing of multiple elements (which I'm not sure select2 support, but you have it just in case)

$(document).ready(function() {
  $("#s1").select2();
  $("#s1").data('originalvalues', []);
  $("#s1").on('change', function(e) {
    var that = this;
    removed = []
    
    $($(this).data('originalvalues')).each(function(k, v) {
      if (!$(that).val()) {
        removed[removed.length] = v;
        return false;
      }
      if ($(that).val().indexOf(v) == -1) {
        removed[removed.length] = v;
      }
    });
    
    
    if ($(this).val()) {
      $(this).data('originalvalues', $(this).val());
    } else {
      $(this).data('originalvalues', []);
    }
    
    console.log("Removed: " + removed)
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.3/select2.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.3/select2.min.js"></script>

<select id="s1" multiple="multiple">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>

3.4.3中的事件是"removed"而不是"select2:removed"

(翻select2 v3.4.3 source code找到的)

$(document).ready(function() {
  $('#mymultiple').select2({
    placeholder: 'pick items'
  });

  $('#mymultiple').on("removed", function(e) {
    alert(e.val);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.3/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.3/select2.css" rel="stylesheet" />
<select id='mymultiple' multiple>
  <option value='one'>One</option>
  <option value='two'>Two</option>
  <option value='three'>Three</option>
</select>