跟踪多个选择选项的先前值

时间:2016-05-05 13:57:54

标签: javascript jquery

我有三个select,我想使用each保存之前选择的所有选项,我已经为其中一个做了但是有什么办法没有为每个人使用相同的代码吗?例如,使用each

jsFiddle



$(function() {
  var previous;

  $('#dropdown1').focus(function(e) {
    previous = $(this).val();
  });

  $('#dropdown1').change(function(e) {
    alert("previous value = " + previous + ", current value = " + $(this).val());
    previous = $(this).val();
  });
});

<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<select id="dropdown1">
  <option>10</option>
  <option>20</option>
  <option>30</option>
</select>

<select id="dropdown2">
  <option>40</option>
  <option>50</option>
  <option>60</option>
</select>

<select id="dropdown3">
  <option>70</option>
  <option>80</option>
  <option>90</option>
</select>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

使用数组维护每个选择的先前值。并修改更改和焦点以定位所有选择元素,并从数组中引用/修改它们各自的先前值:

public class MainActivity extends AppCompatActivity implements AsyncResponse{
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);
        Mytask mt = new Mytask();
        mt.delegate = this;
        mt.execute();
    }

    void processFinish(String output){
        tv.setText(output); 
    }

}

<强> Working Demo

答案 1 :(得分:1)

使用class选择器代替ID

&#13;
&#13;
$(function(){
    var previous;
    
    $('.ddl').focus(function(e){
       previous = $(this).val(); 
    });
    
    $('.ddl').change(function(e){
        alert("previous value = " + previous + ", current value = " + $(this).val());
        previous = $(this).val();
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown1" class="ddl">
    <option>10</option>
    <option>20</option>
    <option>30</option>
</select>

<select id="dropdown2" class="ddl">
    <option>40</option>
    <option>50</option>
    <option>60</option>
</select>

<select id="dropdown3" class="ddl">
    <option>70</option>
    <option>80</option>
    <option>90</option>
</select>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试使用数组

$(function() {
    var previous = [];

    $('#dropdown1').focus(function(e) {
        var data = $(this).val();
        previous.push(data);
    });
});

现在,所有更改都会保留在previous

更新:如果要检索最后一个索引

$('#dropdown1').change(function(e) {
     var last_index_value = previous[previous.lenght];
     alert("previous value = " + last_index_value + ", current value = " + $(this).val());
     previous.push($(this).val());

});