[英]how to find the latest selected item of a multiple select tag using jquery?
I have a <select multiple="multiple" id="multi">
in my website, and I have a script in jquery that has this function: 我的网站上有一个
<select multiple="multiple" id="multi">
,我在jquery中有一个具有此功能的脚本:
$("#multi").on("change",function(){})
I want to access the latest selected item of the select
in this function(the last one selected by user), how can I do that? 我想访问的最新选定的项目
select
在这个函数(最后一个由用户选择的),我该怎么办呢?
To get the last selected by the user, you can do this 要获取用户最后选择的内容,您可以执行此操作
var map = $("#multi").on("change",function(){
var comp = $("#multi option:selected").map(function() {
return this.value;
}).get(),
set1 = map.filter(function(i) {
return comp.indexOf(i) < 0;
}),
set2 = comp.filter(function(i) {
return map.indexOf(i) < 0;
}),
last = (set1.length ? set1 : set2)[0];
map = comp;
// "last" contains the last one selected /unselected
}).find('option:selected').map(function() {return this.value}).get();
var last_value;
$('#multi').change(function() {
last_value = this.val();
alert(last_value);
});
define global variable, and every time ur dropdown change the seletion, u can replace the last selected value with the new one. 定义全局变量,每次你的下拉列表改变选择,你可以用新的值替换最后选择的值。
Less coding with Optimize solution : Why not use the is
function of jquery: 使用Optimize解决方案减少编码:为什么不使用jquery的
is
函数:
$(document).ready(function(){
$('#multi option').click(function(){
if($(this).is(':selected'))
console.log('you have select' + $(this).val());
else
console.log('you have Unselect' + $(this).val());
});
});
How about this 这个怎么样
var = last;
$('#multi').find('option').each(function() {
$(this).click(function() {
if($(this).hasAttr('selected')) {
last = $(this);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.