简体   繁体   English

jQuery-如何选择上一个选择的Select选项?

[英]jQuery - how do you select the previous chosen Select option?

Given this select element: 鉴于此选择元素:

<select id="foo"> 
<option value="1">1</option>
<option value="2">3</option>
<option value="3">3</option>
</select>

And I select the option 1 first, how do I retrieve the value of 1 after I choose 2 in this select dropdown using jQuery? 我首先选择选项1,在使用jQuery的选择下拉列表中选择2后,如何检索1的值?

Just save the previous selection, stored it in a variable or as an attribute on the select itself (attributes are my preference as you can see them in the DOM inspector), example below: 只需保存先前的选择,将其存储在变量中或作为选择本身的属性即可(属性是我的偏好,您可以在DOM检查器中看到它们),如下所示:

$('#foo').change(function(){

    // Get previous value (if any)
    var lastValue = $(this).attr("data-lastvalue"); // or $(this).data("lastvalue"); 

    // Do stuff

    // Save new value
    $(this).attr("data-lastvalue", $(this).val());
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/5kznycjn/2/ JSFiddle: http : //jsfiddle.net/TrueBlueAussie/5kznycjn/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM