将一些rjs和原型代码转换为纯JQuery
因此,railscast 中有以下代码,用于动态添加嵌套模型表单的字段:
这是在应用程序帮助程序中:
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, '#{association}', '#{escape_javascript(fields)}')"))
end
这是 javascript 函数:
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).parent().before(content.replace(regexp, new_id));
}
现在我很好奇如何更改所有这些代码,以便可以纯粹依赖 JQuery 而无需原型或 rjs。
So there's the following code from this railscast for dynamically adding in a field for a nested model form:
This was in the application helper:
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, h("add_fields(this, '#{association}', '#{escape_javascript(fields)}')"))
end
And this was the javascript function:
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g")
$(link).parent().before(content.replace(regexp, new_id));
}
Now I'm curious as to how you would change all of this code so that you could rely purely on JQuery and no prototype or rjs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里唯一与原型相关的是
link_to_function
调用。它的作用是在您的name
文本上创建onclick
处理程序,调用您的add_fields
函数。因此,要成为纯jquery,您应该使用
$().click (function (){...})
方法。然而,具体的实现会有所不同,具体取决于您是想在 html 文件中插入 javascript 还是不引人注目地调用它。The only Prototype related thing here is
link_to_function
call. What it does is createonclick
handler over yourname
text that calls youradd_fields
function.So to be pure jquery you should use
$().click (function (){...})
method instead. However exact implementation will differ depending on whether you want to insert javascript in your html file or call it unobtrusively.