我正在使用jquery ui自动完成功能来获取自动建议。它适用于页面加载的模态弹出窗口。但它不适用于通过ajax加载的模态弹出窗口。请给我一个解决方案来解决这个问题。
g(document).ready(function() {
var dict = [];
var clicked=0;
g(document.body).on("click", "#searchval", function() {
if(clicked==0){
g.ajax({
url: "http://" + window.location.host + "/citypage/modals/cities.php",
method: 'GET',
dataType: 'json',
success: function(data) {
g.each(data, function() {
dict.push(this.toString());
});
}
});
}
clicked=1;
});
g.ui.autocomplete.filter = function(array, term) {
var matcher = new RegExp("^" + g.ui.autocomplete.escapeRegex(term), "i");
return g.grep(array, function(value) {
return matcher.test(value.label || value.value || value);
});
};
g('#searchval').click(function() {
g('#searchval').val('');
});
g(document.body).on("keypress", "#searchval", function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
e.preventDefault();
var siz = g(".ui-autocomplete li").size();
var lival = g(".ui-autocomplete li").first().text().toLowerCase();
var txtval = g("#searchval").val().toLowerCase();
if (lival == txtval) {
g("#selcity").val(txtval);
g("#citysubmit").attr("action", "http://" + window.location.host + "/citypage/modals/ajax_introcookies.php");
g("#citysubmit").submit();
g('#select-city').hide();
g('.ui-autocomplete').hide();
} else {
return false;
}
}
})
.autocomplete({
source: dict,
forceSelect: true,
delay: 200,
typeAhead: true,
response: function(event, ui) {
console.log(ui);
if (ui.content.length == 0) {
g("#empty-message").text("No results found");
} else {
g("#empty-message").empty();
}
},
select: function(event, ui) {
g("#selcity").val(ui.item.value);
var citysubmit = document.citysubmit;
citysubmit.action = "http://" + window.location.host + "/citypage/modals/ajax_introcookies.php";
document.citysubmit.submit();
g('#select-city').hide();
}
}).autocomplete("instance")._renderItem = function(ul,item) {
g(ul).addClass("city_switch_select");
return g("<li>").append(item.value).appendTo(ul);
};
});