1

我有以下 jQuery 循环,但在每个循环动作中我都有用户交互,代码应该等到用户交互完成。是否有可能暂停循环,或者是否有其他可能实现它?

jQuery.each([345, 897, 345 /* ... */], function(index, value) {
    // User interaction, need to wait the user finishing/answer

    // Here is a jQuery UI dialog with an input field in it
    // After the user entered their value and hit the submit button
    // which fires an own callback which could also continue the loop somehow?
});
4

3 回答 3

3

您将需要放弃each并自己处理。一种选择是这样的:

var curIndex = 0;
var ids = [345, 897, 345 /* ... */];

function doNext(){

  // check curIndex here to make sure you haven't completed the list, etc.

  var id = ids[curIndex++];

  // do stuff with this id
}

// THIS IS SOME SORT OF CODE EXECUTED WHEN THE "USER INTERACTION" FINISHES
function interactionDone(){
   doNext();
}
于 2012-05-01T20:59:34.680 回答
1

由于 javascript 是单线程的,因此您可以在每个循环中放置的唯一用户操作是 analertconfirm. 如果这些不能满足您的要求,您需要自己处理每个循环。例如:

//assume foo = [345, 897, 345 /* ... */]
var i = 0;
function handleNextFoo() {
    i++;
    if(i < foo.length) {
        //Do something with foo[i]
        //now we wait for use action to call the callbackFromUserAction()
    }
}
function callbackFromUserAction() {
    //Handle user action
    handleNextFoo();
}

免责声明:应为您的产品处理命名约定以限定变量并使它们更可用。

于 2012-05-01T21:03:00.047 回答
0

只需为自己构建一个快速迭代器对象,这样您就可以轻松处理数组。

var iterator = function(array) {
    this.array = array;
    this.len = array.length;
    this.index = 0;
    return this;
};

iterator.prototype.next = function(callback) {
    callback.call(null, this.array[this.index]);
    this.index++;
    if (this.index == this.len) this.onend.call(null, this.array);
    return this;
};

iterator.prototype.onend = function() {
    alert('done');
};

var iterate = new iterator(arr);

iterate.next(function(val) {
    console.log(val);
});

这是一个演示http://jsfiddle.net/KfrVN/1/

但除此之外,就像 DMoses 指出的那样,只有警报/确认可以停止循环,因为它们是 javascript 用户操作,所以迭代你自己的方式是唯一的方法。

于 2012-05-01T21:15:19.020 回答