我正在编写一些 JavaScript/jQuery 代码,这些代码根据通过 JSON 请求检索到的指定用户代理列表来检测用户代理。
一旦找到匹配项,我希望函数返回 false 并跳出循环,只有在未找到 JSON 文档中的用户代理时才继续返回 true。
我有这个代码...
function checkUserAgent() {
$.getJSON('noapplet-useragents.json', function(data) {
$.each(data, function(key, val) {
if(navigator.userAgent.search(new RegExp(val)) != -1) {
console.log("False!");
return false;
}
});
console.log("True!");
return true;
});
}
// ... call to checkUserAgent() function
然而,当返回false时; true 也被返回。 如何根据需要让第一个 return 停止函数。
console.log()
语句只是 Firebug 的临时语句。
编辑:感谢大家的反馈。由于某种原因,我无法添加评论。
最佳答案
正如我在评论中所说,you cannot return a value from an Ajax call .你必须传递一个回调:
function checkUserAgent(callback) {
$.getJSON('noapplet-useragents.json', function(data) {
var result = true;
$.each(data, function(key, val) {
if(navigator.userAgent.search(new RegExp(val)) != -1) {
console.log("False!");
result = false;
return false;
}
});
callback(result);
});
}
并调用它:
checkUserAgent(function(result) {
// so something with the result
});
关于javascript - 在 JavaScript/JQuery $.each 代码中只返回 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5874537/