Return selected 值更改时不重复 -select

Return selected values on change and not repeat on un-select

如何始终return selected 数组中的选项。更改 return 个包含 select 元素的新数组。

let yo = [];
$(`#filter`).on('change', function() {
   $('option:selected', this).each(function() {
        // console.log(this.value);
        yo.push(this.value);
   });
});
console.log(yo);

现在这个 returns:

首先 select 我的结果是:['one']。 在第 2 select,我得到:['one', 'two']。 在 two unselect 上,我的结果是 ['one', 'two', 'one']。 在 two unselected 我怎样才能让我的结果是 ['one']?

在每次更改时,我可以取回 selected 元素吗?

您只需要在函数内重置 yo 数组。目前,数组只被声明一次,然后你一直向它推送。

$(`#filter`).on('change', function() {
   yo = [];
   $('option:selected', this).each(function() {
        // console.log(this.value);
        yo.push(this.value);
   });
});

这应该可以正常工作,每次运行 on change 函数时,它都会在再次推送之前重置数组。

你可以这样做。

$(`#select`).on("change", function(e) {
  //$(this).val() will get an array of selected values
  console.log($(this).val());
});