如何Jquery每个完成

问题描述 投票:4回答:7

我没有在$ .each()中完成。怎么做的?请帮我

$("element").each(function (i, v) {
        //No problem
    }, function () {
        //How to complete finished ??
        // alert(each finish);
    })
jquery each
7个回答
14
投票

each循环结束后执行代码:

var count = $("element").length;

$("element").each(function (i) {
    // loop
    if (i+1 === count) {
        // this will be executed at the end of the loop
    }
});

13
投票

promise()方法通常用于AJAX,但它可以与each()一起使用来实现你想要的:

$('.element').each(function (key, val) {
    console.log('Do something to each individual .element');
}).promise().done(function () { 
    console.log('Did things to every .element, all done.');
});

3
投票

只需检查元素的索引i,以及.each()循环末尾的元素数。如果它匹配,那么你完成了循环:

$("element").each(function (i, v) {
    // Do all the stuff here

    // Check if you are at the last item
    if($("element").length == i+1) {
        // Code to execute when you are at the last item
    }
});

3
投票

你可以简单地使用$ .when($ .each())。然后(myFunc,failFunc);


0
投票

也许是迟到的回应。但这可能派上用场有一个包可以做你想要的。

var myObject = { // or your array
    1 : 'My first item',
    2 : 'My second item',
    3 : 'My third item'
}

Await.each(myObject, function(key, value){
     //your logic here
});

Await.done(function(){
    console.log('The loop is completely done');
});

0
投票
$(document).ready(function(){
    let control = $(".container").find("#result");
    const setPromise = new Promise(function(resolve,reject){
        if(control.length){
            resolve("Not Problem...")
        }
        else{
            reject("WTF")
        }
    })

    setPromise.then(function(answer){
        console.log(answer)
    }).catch(function(answer){
        console.log(answer)
    })

})

-5
投票

.each电话之后,把你想做的事情放好。你在想它。

$('.el').each(function () {
  $(this).something();
});
alert('Done');
© www.soinside.com 2019 - 2024. All rights reserved.