我正在使用一个简单的下拉菜单,在选择省到城市后更改选项。
我想要的是,为了防止选择省份后关闭下拉菜单,只需更新城市中的选项。
我尝试了这段代码。
$(document).on('click', '#provinceCity', function (e) {
e.stopPropagation();
});
但不适用于我。
这是我的代码
function loadProvince(){
$("#provinceCity").html("<option value=''>Select province</option>");
for (var i=0; i<province.length; i++){
$("#provinceCity").append("<option value='"+province[i]["id"]+"'>"+province[i]["name"]+"</option>");
}
}
$(document).ready(function(){
loadProvince();
$("#provinceCity").change(function(){
var selectedText = $("#provinceCity option:selected").text();
if (selectedText != 'Select province') {
if (localStorage.getItem("selectedProvince") === null) {
localStorage.setItem("selectedProvince", selectedText);
}else if (localStorage.getItem("selectedProvince") !== null) {
localStorage.setItem("selectedCity", selectedText);
var selectedProvinceCity = localStorage.getItem("selectedProvince") + "-" + localStorage.getItem("selectedCity");
$('#provinceCity').append($('<option>', {
value: selectedProvinceCity,
text: selectedProvinceCity,
selected: "selected"
}));
setTimeout(function(){
$('#provinceCity').click(function(){
loadProvince();
$(this).unbind('click');
localStorage.removeItem('selectedProvince');
localStorage.removeItem('selectedCity');
})
}, 500);
}
}
for (var i=0; i<province.length; i++){
if ($(this).val() == province[i]["id"]){
$("#provinceCity").empty();
var cities = province[i]["city"];
$("#provinceCity").html("<option value=''>Select city</option>");
for (var j=0; j<cities.length; j++){
$("#provinceCity").append("<option value='"+cities[j]["id"]+"'>"+cities[j]["name"]+"</option>");
}
}
}
});
$( window ).load(function() {
// Run code
localStorage.removeItem('selectedProvince');
localStorage.removeItem('selectedCity');
});
});