开发者

Manipulate data returned from an AJAX call in jQuery

I have an AJAX call using jQuery:

$('.add a').click(function() {
    $.ajax({
        type: 'POST',
        url: '/ajax/fos',
        context: this,
        datatype: 'html',
        success: function(data){
            $(this).parents('tr').before(data);
        }
    });
});

Once it runs, it adds a new row to a table. The row is verbatim to other rows in the table (structure-wise), but with no data.

I have two other jQuery calls that manipulates the data on the row, but the calls don't work on the new table rows using the AJAX call. Specifically, when a drop-down (select/option) list changes, it does an AJAX call to replace the contents of another drop-down list. Another function removes the row if you want to delete it.

These are the functions that are not working:

$('.fos').change(function() {
    $.ajax({
        type: 'POST',
  开发者_如何学运维      url: '/ajax/courses',
        context: this,
        data:({
            fos_id: $(this).val(),
            name: $(this).find(':selected').text()
        }),
        success: function(data){
            $(this).next().html(data);
        }
    });
});

$('td.remove a').click(function() {
    $(this).parents('tr').remove();
});

Does this have something to do with the AJAX call not registering the new row with DOM or can this not be done?


When you run the code you have on document.ready, jQuery is literally binding the events to all the existing rows at that point in time. To make jQuery aware of possible DOM changes, you need to use jQuery's live functionality. To optimally do what you want, you probably want to use delegate like so:

$("#yourTable").delegate("select.fos", "change", function(){
    // ....
});

$("#yourTable").delegate("td.remove a", "click", function(){
    // ....
});

The way it works is by binding the events to the selector (#yourTable) and letting the events bubble up to it, so that any modifications to the contents of the table are covered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜