ajax回调中未设置变量作用域


function canDeleteFacilitator(facilitatorId, handleData) {
var call = $.ajax({
type: 'GET',
url: urls.candeletefacilitator,
data:{facilitatorId: facilitatorId}
}).done(function (data) {
return handleData(data);
})
}   
var canDeleteText = "";
canDeleteFacilitator(facilitator.value, function (canDelete) {
console.log(canDelete);
if (canDelete == true) {
canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
}
})
console.log(canDeleteText);

canDeleteText未在回调函数中设置。如何更正此范围?

函数中没有返回任何东西。。您还应该在函数的范围内设置var,除非您要将其传入。。。就像。。

canDeleteFacilitator(facilitator.value, function (canDelete) {
var canDeleteText = "";
console.log(canDelete);
if (canDelete == true) {
canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
}
return canDeleteText;
})

从本质上讲,canDeleteText应该留在函数内。。如果你想在函数之外设置它,你需要将函数设置为返回:

var canDeleteText = canDeleteFacilitator( callbacks );

因此,一个实际的用法是将其设置为一个函数,一开始:

function canDeleteFacilitator(canDelete) {
var canDeleteText = "";
console.log(canDelete);
if (canDelete == true) {
canDeleteText = '<button class="badge btn-danger p-2" id="deleteFacilitator" type="button"><i class="fas fa-exclamation-triangle"></i>Delete Permanently</button>';
}
return canDeleteText;
}
var canDeleteText = canDeleteFacilitator(1); // I set it to "true" just to pass the if
console.log(canDeleteText);

最新更新