如何在jquery中使用Delay执行方法

时间:2015-06-02 13:29:03

标签: javascript jquery yii

我在我的表单中使用jquery。点击提交按钮,我调用一个函数QuoteDetailValidation()。我在其中验证字段。但在验证字段后,我尝试获取具有errorActive类的所有字段。但不幸的是我无法得到它。

查看我的代码

$('#saveQuote').on('click', function(event) {

    var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
    QuoteDetailValidation(descriptionData1);

    var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;

    alert(selectors);
    return false;
});

function QuoteDetailValidation(descriptionData1) {

    for (var i = 0; i < descriptionData1.length; i++) {

        var id = descriptionData[i].id;
        var value = descriptionData[i].value;
        var costid = costData[i].id;
        var costValue = costData[i].value;

        $.ajax({
            type: 'GET',
            url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
            data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
            success: function(data) {
                var obj = $.parseJSON(data);
                var cost = obj.cost;
                var desc = obj.desc;

                if (desc != '' || cost != '') {

                    if (cost != '') {

                        $('#' + costid).addClass('errorActive');
                        $('#' + costid).prev().addClass('error');
                        $('#' + costid).next().remove();
                        $('#' + costid).after(cost);
                        $('#' + costid).parent().removeClass('success');
                        $('#' + costid).parent().addClass('error');

                    }

                }
            },
            error: function(data) {
                alert('Your data has not been submitted..Please try again');
            }


        });
    }
}

现在发生了什么,当出现错误时QuoteDetailValidation()将errorActive类附加到字段。

通过var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;我尝试获取具有errorActive类的字段的长度。但在警惕selectors时,它始终会0。但是当我在获得所有errorActive课程之前提醒某些内容时,警告selectors会给我完美的计数。我认为在上课errorActive之前因为警觉而有延迟。所以它给了我数数。如何使用它。请帮忙。提前致谢。

2 个答案:

答案 0 :(得分:4)

您需要在成功回调QuoteDetailValidation方法时执行此操作,因为$.ajax运行异步,并且在调用方法后仍未完成。

    $.ajax({
        type: 'GET',
        url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
        data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
        success: function(data) {
            var obj = $.parseJSON(data);
            var cost = obj.cost;
            var desc = obj.desc;

            if (desc != '' || cost != '') {
                if (cost != '') {
                    $('#' + costid).addClass('errorActive');
                    $('#' + costid).prev().addClass('error');
                    $('#' + costid).next().remove();
                    $('#' + costid).after(cost);
                    $('#' + costid).parent().removeClass('success');
                    $('#' + costid).parent().addClass('error');
                }
            }
            // Here you know that the elements will have the necessary classes.
            var selectors = $('#quote-quoteItems-form .errorActive').length;
            alert(selectors);
        },
        error: function(data) {
            alert('Your data has not been submitted..Please try again');
        }
    });

答案 1 :(得分:4)

您可以确定选择器正确启动所需的确切延迟。无论我们添加什么作为延迟将是假设,并且可以是一些场景的简短 在ajax请求中使用以下一个选项

async: false

如下: -

$.ajax({
            type: 'GET',
            async: false,
            url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
            data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
            success: function(data) {}});

将async设置为false意味着您调用的语句必须在调用函数中的下一个语句之前完成。如果设置async:true(默认值),则该语句将开始执行,并且无论异步语句是否已完成,都将调用下一个语句。 Helpful question

但是我仍然建议你将选择器移动到ajax的成功部分,如下所示: -

$.ajax({
            type: 'GET',
            url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
            data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
            success: function(data) {
                var obj = $.parseJSON(data);
                var cost = obj.cost;
                var desc = obj.desc;

                if (desc != '' || cost != '') {

                    if (cost != '') {

                        $('#' + costid).addClass('errorActive');
                        $('#' + costid).prev().addClass('error');
                        $('#' + costid).next().remove();
                        $('#' + costid).after(cost);
                        $('#' + costid).parent().removeClass('success');
                        $('#' + costid).parent().addClass('error');

                    }

                }
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
//some logice here or move the above in some function and call it here

            },
            error: function(data) {
                alert('Your data has not been submitted..Please try again');
            }


        });

或使用call back functions.

更新:尝试下面的内容它将保持async为true并将计数逻辑保持在$ .ajax之外。

function QuoteDetailValidation(descriptionData1,submitFormOrAddError) {

    for (var i = 0; i < descriptionData1.length; i++) {

        var id = descriptionData[i].id;
        var value = descriptionData[i].value;
        var costid = costData[i].id;
        var costValue = costData[i].value;

        $.ajax({
            type: 'GET',
            url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
            data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
            success: function(data) {
                var obj = $.parseJSON(data);
                var cost = obj.cost;
                var desc = obj.desc;

                if (desc != '' || cost != '') {

                    if (cost != '') {

                        $('#' + costid).addClass('errorActive');
                        $('#' + costid).prev().addClass('error');
                        $('#' + costid).next().remove();
                        $('#' + costid).after(cost);
                        $('#' + costid).parent().removeClass('success');
                        $('#' + costid).parent().addClass('error');

                    }

                }
                submitFormOrAddError(data);
            },
            error: function(data) {
                alert('Your data has not been submitted..Please try again');
            }


        });
    }
}

这样称呼:

$('#saveQuote').on('click', function(event) {

    var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
    QuoteDetailValidation(descriptionData1);


    QuoteDetailValidation(descriptionData1,function(output){
            // here you use the output
            var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; //This line is excuted only after call completes
            alert(selectors);
            //form submit here if error is zero.
        });

        alert("hii");//this  line is executed without waiting for above call..
        return false;
});