使用rails中的远程执行ajax渲染表单中的脚本

时间:2016-01-29 19:39:34

标签: javascript jquery ruby-on-rails ajax

按下此按钮后,我会渲染我的表单

= link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true

通过new.js.erb中的这个脚本

$("#new-link").hide().after('<%= j render("form") %>');

它呈现有效的表单,但是控制此表单的application.js中的脚本却没有。顺便说一下,如果从页面加载生成的表单,而不是js 有其中一个

  $("#noteContent")
          .on("input", function(){
            checkExistNoteContent();
          })
          .ready(function(){
            checkExistNoteContent();
          });

请帮帮我,如何解决这个问题?

rails 4.2.5

DOM

 .container.main-section-index
  %h1.text-center Notes
  -if user_signed_in?
    = link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true
  -else
    = link_to 'Sign up!', new_user_registration_path, :class => "btn btn-primary sign-up-index", :type => "button"
    = link_to 'Log in!', new_user_session_path, :class => "btn btn-primary log-in-index", :type => "button"
  %hr.head-devide
  //other elements

此处的简短版本:

= form_for(@note) do |f|
  .field
    %h5.label-of-content Content
    %br/
    = f.text_area :content, {:class => "form-control content-input", :id => "noteContent"}
    %br/
    .actions
      = f.submit "#{button_label}", {:class => "btn btn-default", :id => "submitNote", :disabled => "disabled"}

1 个答案:

答案 0 :(得分:0)

您需要委派.on函数:

#app/assets/javascripts/application.js
$(document).on("input", "#noteContent", function(){
   checkExistNoteContent();
}).ready(function(){
   checkExistNoteContent();
});

每当您将javascript函数“绑定”到元素上的事件时,元素就会出现在DOM加载中。

如果元素在加载时不存在,JQuery使您能够将事件绑定到另一个元素,并且将该函数委托到子元素(可以稍后加载。)

-

来自docs

  

委派事件的优势在于,它们可以处理稍后添加到文档中的后代元素中的事件。

     

通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委派事件来避免频繁附加和删除事件处理程序。例如,此元素可以是Model-View-Controller设计中视图的容器元素,如果事件处理程序想要监视文档中的所有冒泡事件,则可以是文档。在加载任何其他HTML之前,文档元素在文档的头部可用,因此可以安全地将事件附加到那里而无需等待文档准备就绪。