不完全确定为什么会出错。jQuery新手。根据我见过的所有示例,它应该可以工作,但事实并非如此。
在以下脚本中,函数为变量设置新值,但新值不会保留在函数之外。(控制台日志显示了这一点)
$(document).ready(function() {
// url
var path = location.pathname.split("/"),
pos1_path = path[1] != undefined ? path[1] : false,
pos2_path = path[2] != undefined ? path[2] : false,
pos3_path = path[3] != undefined ? path[3] : false;
//console.log('before: ' + pos2_path);
if (pos1_path = 'article') {
$.post("/js/ajax/article_crumbs.php", { func: "getArticleCrumbs" },
function(data){
pos2_path = data.category;
//console.log('during: ' + pos2_path);
return pos2_path}, "json");
}
//console.log('after: ' + pos2_path);
// navigation
// set category nav to current category
if ( path[2] ) {
$('#category_nav a[class$="' + pos2_path + '"]').toggleClass('current');
}
else {
$('#category_nav a:first').toggleClass('current');
}
});
PHP:
<?php echo json_encode(["category"=>"arts-and-culture"]);
另外,根据控制台打印输出,“之后”打印输出出现在“期间”之前,这是否意味着该函数直到脚本的其余部分结束时才会运行?
编辑:为了澄清,我需要将脚本的{ if(path[1]) setcurrent }部分保留在{ if(pos1_path = 'article') }部分之外,以便如果 pos1_path 不是文章,它会设置值到 URI 中的任何内容..
解决方案根据以下答案:
$(document).ready(function() {
// url
var path = location.pathname.split("/"),
pos1_path = path[1] != undefined ? path[1] : false,
pos2_path = path[2] != undefined ? path[2] : false,
pos3_path = path[3] != undefined ? path[3] : false;
if (pos1_path = 'article') {
//console.log('before: ' + pos2_path);
var data = {id: pos2_path}
$.ajax({
type: 'POST',
url: "/js/ajax/article_crumbs.php",
data: data,
success: function(data){
pos2_path = data.category;
//console.log('during: ' + pos2_path);},
dataType: "json",
async: false
});
}
//console.log('after: ' + pos2_path);
// navigation
// set category nav to current category
if ( path[2] ) {
$('#category_nav a[class$="' + pos2_path + '"]').toggleClass('current');
}
else {
$('#category_nav a:first').toggleClass('current');
}
}