I have an AJAX call using jQuery:
我有一个使用jQuery的AJAX调用:
$('.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.
我还有另外两个jQuery调用来处理行上的数据,但是这些调用不能使用AJAX调用处理新表行。具体来说,当下拉列表(select/option)发生更改时,它会执行一个AJAX调用来替换另一个下拉列表的内容。如果您想要删除该行,则另一个函数删除该行。
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?
这与AJAX调用没有在DOM中注册新行有关吗?
1 个解决方案
#1
3
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:
当您运行在文档上的代码时。准备好了,jQuery实际上是将事件绑定到此时的所有现有行。为了让jQuery意识到可能的DOM更改,您需要使用jQuery的实时功能。为了最优化地做你想做的事,你可能想使用委托,比如:
$("#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.
它的工作方式是将事件绑定到选择器(#yourTable),并让事件冒泡到它,以便对表的内容进行任何修改。
#1
3
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:
当您运行在文档上的代码时。准备好了,jQuery实际上是将事件绑定到此时的所有现有行。为了让jQuery意识到可能的DOM更改,您需要使用jQuery的实时功能。为了最优化地做你想做的事,你可能想使用委托,比如:
$("#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.
它的工作方式是将事件绑定到选择器(#yourTable),并让事件冒泡到它,以便对表的内容进行任何修改。