我在当前项目中使用 RJS。
我有包含数据的表格行,最后一列包含一个按钮,该按钮绑定(bind) javascript click
函数。
现在我必须执行 AJAX 并将新创建的行附加到表中。效果很好。这是 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 保持绑定(bind) 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.
关于javascript - rails 2 : RJS - Javascript events are not working when on page updates remotely,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32594943/