如何打破$ .each

时间:2012-08-25 11:31:29

标签: jquery webmethod

我正在使用$ .each这样的jquery

$.each($('.FormContainer div.MainDiv'), function () {
$.ajax({
      type: "POST",
      url: pageUrl + '/SaveFormResponse',
      data: jsonText,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (response) {
      if (isNaN(response.d) == false) {
          //continue executing $.each further
      }
      else {
          alert(response.d);
          //stop executing $.each further in case of error 
      }
      },
      failure: function (response) {
           alert(response.d);
      }

    });

});

现在的问题是,如果出现错误,我希望$ .each停止执行,但它不会停止,直到它不会遍历所有div

我还尝试维护变量并在每次迭代时检查它的值,并在出错时设置它的值,但仍然无法正常工作

3 个答案:

答案 0 :(得分:0)

$.ajax为您提供结果时,$.each已经完成。请注意,ajax中的第一个“a”代表异步。你可以做的是创建一个递归函数(你没有使用每个元素的特定内容,但我假设你这样做我用$elem):

var $elems = $('.FormContainer div.MainDiv');

(function fetch(i) {
    if(i >= $elems.length) return;  // no elems left

    var $elem = $elems.eq(i);

    $.ajax({
      type: "POST",
      url: pageUrl + '/SaveFormResponse',
      data: jsonText,
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (response) {
        if (!isNaN(response.d)) {
          fetch(i + 1);  // next one
        } else {
          alert(response.d);  // just don't call fetch again
        }
      },
      failure: function (response) {
         alert(response.d);
      }
    });
})(0);  // start with first elem

答案 1 :(得分:0)

没有对它进行测试,但我猜这样的事情会在没有递归或同步行为的情况下进行:

var XHRarray = [];

$.each($('.FormContainer div.MainDiv'), function() {
    var XHR = $.ajax({
        type: "POST",
        url: pageUrl + '/SaveFormResponse',
        data: jsonText,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function(response) {
        if (isInteger(response.d)) {
            //continue executing $.each further
        }else{
            stopAll(); //stop all pending ajax requests
        }
    }).fail(function() {
        stopAll(); //stop all pending ajax requests
    });
    XHRarray.push(XHR);
});

function stopAll() {
    $.each(XHRarray, function(i,e) {
        e.abort();
    }
}​

function isInteger(s){ //checks string for numbers only
    for (var i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}

答案 2 :(得分:-1)

要破坏$ .each(),您需要返回false

$(function() {
    var temp = [0, 1, 2, 3, 4, 5];
    $.each(temp, function(k, v) {
        $('body').append(v);
        if (v == 3) {
            return false;
        }
    });
});

输出:

0123

Read more

但是,如果你想使用这样的异步$ .ajax()调用,你需要决定继续下一个项目还是停止,在回调函数内部。

var currentItem = 0, itemSet = $('.FormContainer div.MainDiv');
function workOnItem(itemNum) {
      if (itemSet[itemNum] != undefined) {
      var item = itemSet[itemNum];
      $.ajax({
            type: "POST",
            url: pageUrl + '/SaveFormResponse',
            data: jsonText,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
            if (isNaN(response.d) == false) {
                  //continue executing $.each further
                  currentItem++;
                  workOnItem(currentItem);
            }
            else {
                alert(response.d);
                //stop executing $.each further in case of error 
            }
            },
            failure: function (response) {
                 alert(response.d);
            }
        });
      }
}
workOnItem(0);