在多个选择框中获取最近的选择

Getting recent selection in multiple select box

本文关键字:选择 获取 最近      更新时间:2023-09-26

我想根据多个选择框的选择来填充内容。我可以得到选择框的所有选定值。使用

$('select').change(function(){
   console.info($(this).val()) // it gives me array
});

但是我只想要用户最近的选择/取消选择。

你可以这样做:

function arr_diff(a1, a2) {
    var a = [],
        diff = [];
    for (var i = 0; i < a1.length; i++)
    a[a1[i]] = true;
    for (var i = 0; i < a2.length; i++)
    if (a[a2[i]]) delete a[a2[i]];
    else a[a2[i]] = true;
    for (var k in a)
    diff.push(k);
    return diff;
}
var oldSelect = [];
$('select').change(function() {
    var changes = arr_diff(oldSelect, $(this).val());
    console.info(changes); // it gives me array
    oldSelect = $(this).val();
});

changes只包含被选中/取消选中的元素

here提琴http://jsfiddle.net/j5rBS/

注:你应该接受一些答案,因为你的录取率非常低

试试这个

// this will set the last selected or deselected option element's value to the select element as a custom attribute "recent" 
$("#selectEl option").click(function(event) {
   $(this).parent().attr("recent", $(this).val());
});

$("#selectEl").attr("recent"); // returns the last selected/deselected option value or undefined if attribute recent is not present

或者简单地只是在select时获取数组的第一个索引。

$(function(){
$('select').change(function(){
   var opt=$(this).val();
    $("span").text(opt[0]);
});
})
http://jsfiddle.net/jMw92/10/