我想知道我的代码有什么问题?它只是无法正常工作。语法对我来说很好——基本上,如果加载的页面上存在一个名为“map_canvas”的 div,那么应该调用一个名为 initialize_google_maps 的函数。
但是,即使页面上不存在 map_canvas div,有时也会调用 initialize_google_maps 函数。更具体地说 - 它总是在第一次单击链接时被调用,即使没有 map_canvas 存在,然后它的行为也正确。
$(document).on("ready", function(){
console.log('load ajax when document starts');
var ajax_loaded = (function(response) {
$(".page-content")
.html($(response).filter(".page-content"));
$(".page-content .ajax").on("click",ajax_load);
});
//the function below is called by links that are described with the class 'ajax', or are in the div 'menu'
var history = [];
var current_url_method;
var ajax_load = (function(e) {
console.log('load ajax on clicks');
e.preventDefault();
history.push(this);
var url =$(this).attr("href");
var method = $(this).attr("data-method");
if (current_url_method != url + method) {
console.log('url + method');
current_url_method = url + method;
$.ajax({
"url": url,
"type": method,
"success": ajax_loaded,
});
}
if ($("#map_canvas").length > 0)
{
console.log('ajax 2 - map_canvas is detected');
initialize_google_maps();
}
});
$("#menu a").on("click",ajax_load);
$(".ajax").on("click",ajax_load);
$("#menu a.main").trigger("click");
$(".search-box form").on("submit", form_submit);
});