是否有可能找到触发了.change()的值?

时间:2016-12-01 07:46:59

标签: jquery

<select>代码中,是否可以从中找到.change()触发的值

3 个答案:

答案 0 :(得分:5)

使用变量缓存前一个值。

&#13;
&#13;
// bind change event handler to the eleemnt 
// and cache the current value in `prev`
var prev = $('#test').change(function() {
  // get previous value from `prev`
  console.log('prev : ' + prev + ' , current : ' + this.value);

  //... do the rest here

  // update the `prev` variable with current value
  prev = this.value;
}).val(); // get the default value
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test">
  <option value="1">1</option>
  <option value="11">11</option>
  <option value="111">111</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

以下是一个示例,您只需要在页面加载时获得value的{​​{1}},然后每次更改时都只需使用新值更新此变量。

在任何更改事件中,变量select在更改前保留先前的值。

currValue
var currValue = $('select').val();

$('select').on('change',function(){
  var newValue = $(this).val();
  alert('value Before change : '+ currValue);
  alert('value After change : '+ newValue);
  
  currValue = newValue;
});

答案 2 :(得分:1)

如果我没错,这就是你要求的:

&#13;
&#13;
(function () {
    var previous;

    $("select[name=test]").focus(function () {
        // Store the current value on focus, before it changes
        previous = this.value;
    }).change(function() {
        // Do soomething with the previous value after the change
        document.getElementById("log").innerHTML = "<b>Previous: </b>"+previous;
        
        previous = this.value;
    });
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="test">
    <option value="stack">Stack</option>
    <option value="overflow">Overflow</option>
    <option value="my">My</option>
    <option value="question">Question</option>
</select>
<div id="log"></div>
&#13;
&#13;
&#13;