该函数执行时返回一个未定义的值。我希望它在页面加载时返回 true,如果未加载则返回 false:
function JLoad (url) {
var uri = url + ' #div';
$("#div").load(uri, {'bd': '1'}, function(response, status, xhr){
if (status != "error"){
if (window.history && window.history.pushState)
{
window.history.pushState({}, 'Test', url);
}
else
{
window.location.hash='!/'+url;
}
return true;
}else{
return false;
}
});
};
这是用于请求该函数的代码的一部分:
$(document).ready(function() {
$("a").on("click", function() {
var url = $(this).attr("href").replace('./', '');
console.log(JLoad(url));
return false;
});
});
最佳答案
因为 jQuery.load() 是异步的,所以重写您的函数以接受回调。
function JLoad (url, cb) {
var uri = url + ' #div'
$("#div").load(uri, {'bd': '1'}, function(response, status, xhr){
if (status != "error"){
if (window.history && window.history.pushState)
{
window.history.pushState({}, 'Test', url);
}
else
{
window.location.hash='!/'+url;
}
cb(true);
} else{
cb(false);
}
});
}
然后:
$(document).ready(function() {
$("a").on("click", function() {
var $link = $(this),
url = $link.attr("href").replace('./', '');
JLoad(url, function(successful) {
if (successful) {
$("a").removeClass("active");
$link.addClass("active");
}
});
});
});
关于javascript - JQuery 中未定义的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16970535/