如何获取取消选择选项的值



假设我有一个这样的选择:

<select id="cars" multiple>
<option value="1">Ferrari</option>
<option value="2">Lamborghini</option>
</select>

想象一下,现在两个值都被选中了,我取消选择Ferrari,我如何检索取消选择选项的值,在这种情况下是Ferrari

我尝试过:

$('#cars option').on('click', function(){
console.log($(this).val());
});

但该事件从未被激发,我也尝试过使用change,这是被激发的,但我只得到选定的值,而不是取消选定的值。

您可以结合类的使用来跟踪哪些元素被选中,哪些元素不再被选中。

var $cars = $('#cars').on('change', function(){
// find the options that were selected, but are not now
var $deselected = $cars.find('option.selected:not(:checked)');

// add the selected class to the selected options for tracking
$cars.find('option:checked').addClass('selected');
// remove the selected class to untrack them
$deselected.removeClass('selected');

// report which options were deselected
console.log($deselected.get());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="cars" multiple>
<option value="1">Ferrari</option>
<option value="2">Lamborghini</option>
</select>

最新更新