我想检查多项选择的更改状态是否取消选择或选择。
伪码:
$(document).on('change', '.mySelect', function (event) {
if(event === 'selected'){
alert("You have selected this item.");
} else {
alert("You have deselected this item.");
}
});
这样的事情并不奏效。我怎样才能查看天气事件是"选择"事件或"取消选择"事件
修改
这是一个jsfiddle DEMO
答案 0 :(得分:3)
尝试在更改时保存select元素的当前状态:
http://jsfiddle.net/Wexcode/a4mf8akj/5/
function wasDeselected (sel, val) {
if (!val) {
return true;
}
return sel && sel.some(function(d) { return val.indexOf(d) == -1; })
}
$(document).on('change', 'select', function (event) {
var message,
$select = $(event.target),
val = $select.val(),
sel = $('select').data('selected');
// Store the array of selected elements
$select.data('selected', val);
// Check the previous and current val
if ( wasDeselected(sel, val) ) {
message = "You have deselected this item.";
} else {
message = "You have selected this item.";
}
alert(message);
});
答案 1 :(得分:2)
诀窍是跟踪所选的选项长度..
var $select = $('select');
$select.change(function () {
// Last saved state;
var lastState = $(this).data('total'),
// New state;
changedState = $(this).find('option:selected').length,
txt = (lastState < changedState ?
'selected' : (
lastState > changedState ?
'Deselected' :
'Only one option is selected'));
// save state
$(this).data('total', changedState);
$('#console').append('<p>' + lastState + ' => ' + changedState + '<span>' + txt + '</span></p>');
// Initializing tracker
}).data('total', $select.find('option:selected').length);
试试这个here