我有以下代码来触发链选择元素。我想将cityID更改为 $(this).val(); 的值,如果未选择property_city,则将其更改为从数据库中提取的值。这可能吗?
<script>
$( "select[name='property_city']" ).change(function () {
var cityID = $(this).val();
if(cityID) {
$.ajax({
url: "/pages/chain_select/get_postal_town.php",
dataType: 'Json',
data: {'id':cityID},
success: function(data) {
$('select[name="postal_town"]').empty();
$.each(data, function(key, value) {
$('select[name="postal_town"]').append('<option value="'+ key +'" >'+ value +'</option>');
});
}
});
}else{
$('select[name="postal_town"]').append('<option value="'+ key +'" >'+ value +'</option>');
}
});
答案 0 :(得分:0)
据我所知,您希望存储以前的cityID,并且当用户选择从DB中提取的相同ID时,您不想从DB中提取任何内容。
var cities = {};
$( "select[name='property_city']" ).change(function () {
if(cities[$(this).val()]) {
cities[$(this).val()].forEach(function(key, value) {
$('select[name="postal_town"]').append('<option value="'+ key +'" >'+ value +'</option>');
});
} else {
$.ajax({
url: "/pages/chain_select/get_postal_town.php",
dataType: 'Json',
data: {'id':cityID},
success: function(data) {
$('select[name="postal_town"]').empty();
$.each(data, function(key, value) {
$('select[name="postal_town"]').append('<option value="'+ key +'" >'+ value +'</option>');
});
cities[$(this).val()] = data;
}
});
}
});