我有一个函数返回xml文件中属性的最高值
返回的值总是0,所以我认为JQuery函数下的值不知道它内部发生了什么.这是功能:
function findHighestValue(url,attr){
var highestValue = 0;
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: function(xml) {
$(xml).find("achievement").each(function(){
var value = $(this).find(attr).text();
value = value*1;//typecast
console.log("value: "+value);//shows correct value
console.log("highestValue in ajax: "+highestValue);//shows correct value
if (value >= highestValue){
highestValue = value;
console.log("Value higher highesValue detected!");//works as intended
}
});
}
});
console.log("Highest Value: "+highestValue);// is 0 again
return highestValue;//always returns 0
}
Run Code Online (Sandbox Code Playgroud)
因为它是一个ajax请求,所以最后两行在success方法中的行之前被命中.
除非设置,否则无法从ajax请求返回值 async: false
您需要通过成功回调处理该值,而不是尝试返回它.