select下拉怎么撤销本次的选择更改, 还原为上次选择的值.使用jq操作
假设我们有个需求是, 当选择到某个选项时, 弹出确认框提示.用户选择是,那么值就改变, 如果选择否, 那么我们需要还原为上次的选择.实现如下:(相比使用全局变量,我们可以用$.data来优雅处理)
$('select').change(function() {
let selected = $(this).val();
if (selected == 'beer') {
if (!confirm('Are you sure?')) {
$(this).val($.data(this, 'current'));
return false;
}
}
$.data(this, 'current', $(this).val());
});