我对我的脚本有点困惑:我试图通过 jQuery 和 AJAX 在我的页面中进行实时搜索。在此示例中,我想在 2 个站点中搜索关键字,并且当我找到某些内容时我想中断 AJAX 循环:
var urls = [
'http://docs.db-dzine.com/woocommerce-advanced-categories/',
'http://docs.db-dzine.com/woocommerce-catalog-mode/',
];
var found = false;
$.each(urls, function(i, url) {
ajaxSearchPage(url, keyword, function(found) {
console.log(found);
if(found) {
return true;
}
});
if(found) {
return true;
}
});
我不知道如何打破这里的循环...请帮忙。
还有我的 AJAX 函数:
var ajaxSearchPage = function(url, keyword, callback) {
$.ajax({
url: url,
type: "GET",
dataType: "html",
success: function(response) {
// Do not load images
var page = response.replace(/<img/gi, '<noload');
// Create parsable body for jQuery
var body = $('<div id="body-mock">' + page.replace(/^[\s\S]*<body.*?>|<\/body>[\s\S]*$/ig, '') + '</div>');
// Find the keyword in content
var content = body.find('#content:containsNC("'+ keyword +'")');
if(content.length > 0) {
searchResultsWrapper.show();
callback(true);
} else {
callback(false);
}
}
});
};
最佳答案
We can break the
$.each()
loop at a particular iteration by making the callback functionreturn false
. Returningnon-false
is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
关于javascript - jQuery 在 AJAX 请求中使用回调中断循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39041276/