我在this railscast上看到了一些评论,说这个解决方案不适用于Rails3和jQuery,但就是不清楚。这是我在控制台中得到的错误:
Uncaught ReferenceError: add_fields is not defined
(anonymous function)485:98
onclickd它指向了这个很长很奇怪的链接:<a href="#" onclick="add_fields(this, 'comment_titles', '&lt;p class=\&quot;fields\&quot;&gt;\n&lt;label for=\&quot;video_comment_titles_attributes_new_comment_titles_title\&quot;&gt;Comment Title:&lt;\/label&gt; \n&lt;input id=\&quot;video_comment_titles_attributes_new_comment_titles_title\&quot; name=\&quot;video[comment_titles_attributes][new_comment_titles][title]\&quot; size=\&quot;30\&quot; type=\&quot;text\&quot; /&gt;\n&lt;input id=\&quot;video_comment_titles_attributes_new_comment_titles__destroy\&quot; name=\&quot;video[comment_titles_attributes][new_comment_titles][_destroy]\&quot; type=\&quot;hidden\&quot; value=\&quot;false\&quot; /&gt;&lt;a href=\&quot;#\&quot; onclick=\&quot;remove_fields(this); return false;\&quot;&gt;remove&lt;\/a&gt;\n&lt;input id=\&quot;add_comment_title\&quot; name=\&quot;commit\&quot; type=\&quot;submit\&quot; value=\&quot;Add\&quot; /&gt;\n &lt;div class=\'hint\'&gt;Let your listeners know what comments you want by adding a guiding title for them. Pose a question, ask for feedback, or anything else!&lt;\/div&gt;\n&lt;\/p&gt;'); return false;">New Comment Title</a>
这是我的视频展示视图中的这个链接:
<%= link_to_add_fields "New Comment Title", f, :comment_titles %>这是我的应用程序助手中的link_to_add_fields方法:
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这是我的application.js中的添加字段功能:
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));
}我几乎是从铁路广播中复制和粘贴的,所以我不确定发生了什么。
我该如何解决这个问题呢?你还想看什么其他的代码?
发布于 2011-04-04 14:47:59
所以看起来是这样的:
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));
}必须在document.ready()块的外部。
https://stackoverflow.com/questions/5534763
复制相似问题