$(document.body).on('change','.product-dropdown',function(){
var selectVaule = $(this).val();
if(selectVaule){
alert(selectVaule+ 'select');
}
});
上面的代码返回数组中的所有选定值。我只想在多个选择2上获得最新的点击值。
答案 0 :(得分:8)
查看select2:select
事件并使用event.params.data
也有select2:unselect
。
$('select').select2()
$('select').on('select2:select', function(e) {
var data = e.params.data;
console.log(data.id);
console.log(data.text);
});
$('select').on('select2:unselect', function(e) {
var data = e.params.data;
console.log(data.id);
console.log(data.text);
});

<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/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />
<select multiple="multiple">
<option></option>
<option value="1">foo</option>
<option value="2">bar</option>
<option value="3">foo bar</option>
</select>
&#13;
答案 1 :(得分:1)
不幸的是,据我所知,没有优雅的解决方案。
基本上只是跟踪所有值并查看哪些是新的(请注意,lastClicked可以是一个列表,因为可以一次选择多个值):
var lastClicked= null;
var prevClicked = [];
$('.product-dropdown').change(function(){
var curClicked = this.val();
lastClicked = curClicked.filter(function(x) { return prevClicked.indexOf(x) < 0 });
});
答案 2 :(得分:0)
var prevClicked = [];
var curClicked = [];
var difference = [];
$('.product-dropdown').change(function(){
curClicked = $(this).val();
if(curClicked == null){
curClicked=[];
}
clickType = getClickType();
var clickedValue = diffArray(curClicked, prevClicked);
console.log(clickType + ' ' + clickedValue);
prevClicked = curClicked;
});
function getClickType(){
var prevLen = prevClicked.length;
var CurLen = curClicked.length;
if(prevLen < CurLen){
return 'select';
}
else{
return 'unselect';
}
}
function diffArray(a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}