我有这段代码:
$(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事件中为全局变量赋值? 请帮忙。谢谢:)
答案 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;
答案 3 :(得分:0)
$(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;