如何将onchange上的值传递给jquery中的另一个onchange事件

时间:2017-02-02 05:12:40

标签: javascript jquery

我有这段代码:

$(document).ready(function(){
  var country;
  $('#selectCountry').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var country= this.value;
  });

  $('#selectedPlace').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var place = this.value;
    console.log(country);
    console.log(place);
  });
});

我想在选择地点或触发selectedCountry onchange事件时获取selectPlace值。 我尝试了这段代码,但country未定义

如何从onchange事件中为全局变量赋值? 请帮忙。谢谢:)

4 个答案:

答案 0 :(得分:2)

country selectedplace被解雇时,您可以直接获得onchange的价值

$('#selectedPlace').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var place = this.value;
    console.log( $('#selectCountry').val());
    console.log(place);
  });

答案 1 :(得分:0)

  $(document).ready(function(){
     var country
      place;

 $('#selectCountry').on('change', function (e) {
  country = $('#selectCountry').val();
});

 $('#selectedPlace').on('change', function (e) {
 var place = $('#selectedPlace').val();
 console.log(country);
 console.log(place);
 });
});

答案 2 :(得分:0)

var功能中的var country= this.value;移除$('#selectCountry').on('change', function (e) { });。刚设为全球。



$(document).ready(function() {
  var country;
  $('#selectCountry').on('change', function(e) {
    var optionSelected = $("option:selected", this);
    country = this.value;
  });

  $('#selectedPlace').on('change', function(e) {
    var optionSelected = $("option:selected", this);
    var place = this.value;
    console.log(country);
    console.log(place);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="selectCountry">
  <option value=0>Select</option>
  <option value=A>A</option>
  <option value=B>B</option>
</select>
<select id="selectedPlace">
  <option value=0>Select</option>
  <option value=a>a</option>
  <option value=b>b</option>
</select>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

&#13;
&#13;
$(document).ready(function(){
  var country;
  $('#ddlCountry').on('change', function (e) {
     country= $('#ddlCountry').val()
  });

  $('#ddlPlace').on('change', function (e) {
    var place = $('#ddlPlace').val();
    console.log(country);
    console.log(place);
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="ddlCountry">
  <option value=0>Select</option>
  <option value=India>India</option>
  <option value=Usa>Usa</option>
</select>
<select id="ddlPlace">
  <option value=0>Select</option>
  <option value=Mumbai>Mumbai</option>
  <option value=Colorado>Colorado</option>
</select>
&#13;
&#13;
&#13;