jQuery行函数未定义

时间:2015-04-16 21:18:38

标签: javascript jquery ruby-on-rails-4 nested-forms

我在TypeError: $(...).data(...)行中有一个$(this).before($(this).data('daw_preguntaes').replace(regexp, time));}。我正在使用Railscast 196,但此功能不会加载我想要显示的新字段。我不知道在data(fields)

中放什么
jQuery ->
        $('form').on 'click', '.add_fields', (event) ->
        time = new Date().getTime()
        regexp = new RegExp($(this).data('id'),'g')
        $(this).before($(this).data('fields').replace(regexp,time))
        event.defaultPrevented()

Survay View

<%= f.fields_for :questions do |builder| %>
  <%= render 'questions_fields', f: builder %>
<% end %>
<%= link_to_add_fields "New question",f,:questions  %>

问题视图

<fieldset>
    <%= f.label :content, 'Question' %>
    <%= f.text_area :content %>
    <%= f.check_box :_destroy %>
    <%= f.label :_destroy, "Delete" %>
</fieldset>

1 个答案:

答案 0 :(得分:0)

在RailsCasts#403中,Ryan使用CoffeeScript文件中的编辑代码。我将_question_fields命名为_questions_fields

的CoffeeScript

$(document).on 'click', 'form .remove_fields', (event) ->
  $(this).prev('input[type=hidden]').val('1')
  $(this).closest('fieldset').hide()
  event.preventDefault()

$(document).on 'click', 'form .add_fields', (event) ->
  time = new Date().getTime()
  regexp = new RegExp($(this).data('id'), 'g')
  $(this).before($(this).data('fields').replace(regexp, time))
  event.preventDefault()

辅助

def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
        render(association.to_s.singularize + "_fields", f: builder)
    end
    link_to(name,'#', class: "add_fields", data: {id: id, fields: fields.gsub("\n","")}) 
end