首页 > 解决方案 > 如何获得取消选择的选项的价值?

问题描述

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

<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,这被触发了,但我只得到选定的值而不是取消选择的值。

标签: javascriptjqueryselect

解决方案


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

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>


推荐阅读