从多个选择框中获取最后更改的选项元素

时间:2018-01-26 19:06:01

标签: javascript jquery html forms event-handling

我需要使用jQuery或crossbrowser native js code的多选框中的last(1)更改选项元素。

(1)last = time not order!

<form id="form-with-msb">
    <select multiple id="multiple-select-box">
        <option value="all">All</option>
        <option value="1">xxx</option>
        <option value="2">yyy</option>
        <option value="3">zzz</option>
    </select>
</form>

$( "#form-with-msb" ).on( "change", "#multiple-select-box", function() {
  // get last changed option element from multiple select box
});

2 个答案:

答案 0 :(得分:1)

您可以使用data属性存储以前选择的选项。

<强>即:

<select data-last='' ...>...</select>

每次onChange次调用都会将所选选项存储到data属性中。

$("#form-with-msb").on("change", "#multiple-select-box", function() {
  var last = $(this).data('last');
  console.log(last.split(','));

  var selected = [];
  $(this).children(':selected').each(function(idx, opt) {
    selected.push($(opt).text());
  });
  $(this).data('last', selected.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form-with-msb">
  <select data-last='' multiple id="multiple-select-box">
        <option value="all">All</option>
        <option value="1">xxx</option>
        <option value="2">yyy</option>
        <option value="3">zzz</option>
    </select>
</form>

答案 1 :(得分:-1)

您可以定义一个数组对象来记录用户执行的所有操作。然后获取最后一个数组对象作为最后一个更改。即使您可以通过此机制实现重做/撤消功能。

var G_ACTION_CACHE = []
$( "#form-with-msb" ).on( "change", "#multiple-select-box", function() {
  // get last changed option element from multiple select box
  if(G_ACTION_CACHE.length===0){
    console.log("NO ACTION BEFORE");
  }
  else{
    console.log(G_ACTION_CACHE[G_ACTION_CACHE.length-1]);
  }
  var current_actions = [];
  $.each($( "#form-with-msb" ).find("option:selected"), function(index, item) {
    current_actions.push({'ID':index, 'VALUE':$(item).text()});
  });
  G_ACTION_CACHE.push(current_actions);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form-with-msb">
    <select multiple id="multiple-select-box">
        <option value="all">All</option>
        <option value="1">xxx</option>
        <option value="2">yyy</option>
        <option value="3">zzz</option>
    </select>
</form>