Append语句每次都继续执行

时间:2014-06-02 11:03:37

标签: jquery

每次警报都会继续追加,而我只希望它只追加一次

这就是我整个代码的样子,还在学习东西!

// 1. listen for submit 
jQuery('.save').submit(function(event) {

    // 2.  get the form data
    var formData = {
        'editor_content' : jQuery('.jqte_editor').text()
    };
    // grab the form url
    url = jQuery('.save').attr('action');

     //  Show spinner as request start
    $('.spinner').show();

    //  4. process the form

    jQuery.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : url, // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back from the server
                     encode          : true
    })
        // using the success promise callback
        .success(function(data) {
            // stop spinner as request completes
                    $('.spinner').hide();

            // here we will handle errors and validation messages
            if(! data.success)
            {

//每次按下提交按钮

时都会继续追加
                $('.save').append('<div class="warning alert">'+data.editor_content+'</div>');
            }
            });

    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});

2 个答案:

答案 0 :(得分:0)

您可以验证是否已添加.alert框并阻止再次添加..

if(!data.success && $('.save > .warning.alert').size() == 0){
   $('.save').append('<div class="warning alert">'+data.editor_content+'</div>');
}

答案 1 :(得分:0)

var warned = false;
if (! data.success){
    if (! warned)
       $('.save').append('<div class="warning alert">' + data.editor_content + '</div>');
       warned = true;
    }
}