所以我有宾果游戏的脚本。我在另一个函数中运行我的函数之一时遇到问题。我的想法是让我的 checkBingo() 函数在 .click() 函数之外定义。有一些 ajax 在工作,所以我不确定这是否也在这里发挥作用。看起来像:
$(document).ready(function(){
function checkBingo() {
$.ajax({
url: '/check-bingo',
type: 'GET',
success: function(data){
return data;
}
}):
}
$('#div').click(function() {
// Some stuff gets done here
$.ajax({
url: '/tile',
type: 'GET',
success: function(data){
// Does some stuff with data, then needs to check if there's a bingo.
var isBingo = checkBingo();
if (isBingo == 'something') {
// Displays something specific on the page.
} else {
// Displays other things on the page.
}
}
}):
});
让我困惑的是,isBingo 永远不会分配返回的信息。我认为这可能是因为查询运行得不够快,所以我尝试将变量放入循环中,直到它分配了一些东西,然后控制台告诉我,我的 checkBingo() 在 .click 函数中没有定义。我不确定这是否只是我的一个愚蠢的语法错误,或者我正在做的事情是否不可能。
有人可以验证这确实是可能的,并且我可能只需要检查它是否存在语法错误?
最佳答案
因为这一行:
var isBingo = checkBingo();
...正在调用一个进行异步调用且不返回任何内容的函数 (checkBingo
),isBingo
将是未定义的。
解决此问题的一种方法是将回调函数传递给 checkBingo
,因为 JavaScript 允许函数像数据一样传递,并且当从服务器:
function checkBingo(callback) {
$.ajax({
url: '/check-bingo',
type: 'GET',
success: function(data){
callback(data);
}
// or you could just do:
// success: callback,
});
}
// ....
success: function(data){
checkBingo(function (isBingo) {
if (isBingo == 'something') {
// Displays something specific on the page.
} else {
// Displays other things on the page.
}
});
另一种方法,即使代码是不同步执行的方法是利用 jQuery 的 Ajax API 的更高版本返回一个允许这种编码风格的 Promise 对象的事实:
$(document).ready(function(){
function checkBingo() {
return $.ajax({
url: '/check-bingo.txt',
type: 'GET'
});
}
$('#div').click(function() {
// Some stuff gets done here
$.ajax({
url: '/tile.txt',
type: 'GET',
success: function(data){
var checkingBingo = checkBingo();
checkingBingo.done(function (isBingo) {
if (isBingo == 'something') {
alert('a');
// Displays something specific on the page.
} else {
alert('b');
// Displays other things on the page.
}
});
}
});
});
});
除了需要将几个冒号转换为分号,并在“#div”代码前面添加 jQuery $
之外,还需要注意以下两个方面:
- 我在 Ajax 调用中添加了“.txt”扩展名,以防该扩展名仅隐藏在您的系统中。
- 代码
$('#div')
假定您的页面上有一个 ID 设置为“div”的元素。如果您希望所有div
元素都可点击,则只需执行$('div')
即可。
关于Javascript 整理嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16472620/