这是raislcasts.com complex-form-examples中关于动态地将字段添加到表单的函数。该函数使用rails 3.1.3和jquery运行。
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, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
end
该协会是一个象征,必须是。这\"...\"
#{..}
的目的是什么?删除它会导致错误。
答案 0 :(得分:6)
目的是转义出现在相同类型的引号字符内的引号字符,以确保字符串不以此字符结尾
适当使用的示例
"This is a \"quote\""
=> This is a "quote"
'This is a \'quote\''
=> This is a 'quote'
"This is a 'quote'"
=> This is a 'quote'
'This is a "quote"'
=> This is a "quote"
答案 1 :(得分:3)
反斜杠用于转义双引号。这样你就可以在字符串中使用任意数量的双引号(以反斜杠为前缀)......
前:
var test = "Bobby said "Hello!" to the crowd.";
-> will give you an syntax error
var test = "Bobby said \"Hello!\" to the crowd.";
-> double quote for (Hello!) is escaped using backslash