javascript - 如何获得取消选择的选项的价值?
问题描述
假设我有一个这样的选择:
<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>
推荐阅读
- jquery - 为什么原生引导程序不能与 Angular 一起使用?
- java - org.springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数“full_text”不存在。我正在尝试添加博客
- reactjs - 无法在反应中更改 svg 图标的高度
- recursion - 方案编程:与列表交互时函数中的合同违反错误
- stm32 - STM32:disable UART interrupt can't use UART in DMA mode
- wordpress - Wordpress - 通过日期选择器自定义字段将帖子设置为草稿
- javascript - 从数组javascript中制作具有唯一名称的div id
- flutter - Flutter:如何将类似应用程序的聊天通知与 Firebase 消息传递集成
- python - 无法将 csv 文件加载到 heroku 中的 postgres 表中 - 错误:整数类型的输入语法无效:
- php - php WHERE-IN 中的 mysql 语句不起作用