Rails2:RJS - Javascript 事件在远程页面更新时不起作用
Rails2: RJS - Javascript events are not working when on page updates remotely
我在当前项目中使用 RJS。
我有 table 行数据,最后一列包含一个绑定 javascript click
函数的按钮。
现在我必须执行 AJAX 并将新创建的行附加到 table。它工作正常。这是 create.rjs
模板文件。
page.insert_html(:bottom, "products", :partial => "product_row.html.erb", :locals => {:product => @product})
JS代码:
jQuery(document).ready(function(){
jQuery("button.add_color").click(function(){
alert('ok');
});
});
一切正常,除了 javascript click
事件对新创建的行不起作用。
请帮助如何为 AJAX 新添加的 DOM 保持绑定 javascript 事件?
我认为你应该使用 jQuery 的 .delegate
method:
jQuery(document).ready(function(){
jQuery('body').delegate('button.add_color', click, function(){
alert('ok');
});
});
来自 delegate
的文档:
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
我在当前项目中使用 RJS。
我有 table 行数据,最后一列包含一个绑定 javascript click
函数的按钮。
现在我必须执行 AJAX 并将新创建的行附加到 table。它工作正常。这是 create.rjs
模板文件。
page.insert_html(:bottom, "products", :partial => "product_row.html.erb", :locals => {:product => @product})
JS代码:
jQuery(document).ready(function(){
jQuery("button.add_color").click(function(){
alert('ok');
});
});
一切正常,除了 javascript click
事件对新创建的行不起作用。
请帮助如何为 AJAX 新添加的 DOM 保持绑定 javascript 事件?
我认为你应该使用 jQuery 的 .delegate
method:
jQuery(document).ready(function(){
jQuery('body').delegate('button.add_color', click, function(){
alert('ok');
});
});
来自 delegate
的文档:
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.