2

I'm sure jQuery works fine, but for some reason it isn't for me. I can't even put it into a jsFiddle because it doesn't like Ajax, but my statements involving $(this).children are not working at all. I'm not getting any errors... what am I doing wrong?

JS

$('.submitNewOrder').submit( function() {
    $(this).children('input[type=\"submit\"]').prop('disabled',true); // Doesn't work
    $(this).children('.saving').fadeIn('fast');  // Doesn't work
    $.ajax({
        url: 'scripts/submitNewOrder.php?catID=1',
        data: newOrder,
        type: 'POST',
        mode: 'abort',
        success: function(){
            $(this).children('.saving').fadeOut('fast', function() { // Doesn't work
                $(this).children('.success').fadeIn('fast'); // Doesn't work
            });
        },
        error: function(){
            $(this).children('.error').fadeIn('fast'); // Doesn't work
        }
    });
    return false;
});

HTML

<form class="submitNewOrder">
    <p>
    <input type="submit" value="Save order" />
        <span class="saving" style="display:none">Saving changes...</span>
        <span class="success" style="display:none">Saved!</span>
        <span class="error" style="display:none">There was a problem saving :(</span>
    </p>
</form> 
4

3 回答 3

8

Try replacing the children with find like:

$('.submitNewOrder').submit(function () {
    var $this = $(this);
    $this.find('input[type=\"submit\"]').prop('disabled', true); 
    $this.find('.saving').fadeIn('fast'); 
    $.ajax({
        url: 'scripts/submitNewOrder.php?catID=1',
        data: newOrder,
        type: 'POST',
        mode: 'abort',
        success: function () {
            $this.find('.saving').fadeOut('fast', function () { 
                $this.find('.success').fadeIn('fast'); 
            });
        },
        error: function () {
            $this.find('.error').fadeIn('fast'); 
        }
    });
    return false;
});
于 2013-07-02T11:11:30.957 回答
3

Use context option of ajax and use .find() instead of .children():

$.ajax({
        url: 'scripts/submitNewOrder.php?catID=1',
        data: newOrder,
        type: 'POST',
        mode: 'abort',
        context: this, //<< HERE so in callback functions, 'this' refers to the object, not options object of ajax call
        success: function(){
            $(this).find('.saving').fadeOut('fast', function() {
                $(this).find('.success').fadeIn('fast');
            });
        },
        error: function(){
            $(this).find('.error').fadeIn('fast');
        }
    });
于 2013-07-02T11:05:44.810 回答
0

In submit this points to the form element. The elements you are looking for are not children of form, but children of <p>. Change your expressions to $(this).find(...), which will search further than one level down the tree.

于 2013-07-02T11:13:35.423 回答