jquery - 如何(重新)绑定(bind)以在 .load(ed) 表单上提交按钮/表单

标签 jquery ruby-on-rails

在学习如何实现不显眼的 js(使用 Rails 和 jQuery)的早期阶段,我遇到了如何在 .load(ing) 包含表单的新内容之后(重新)绑定(bind)提交按钮/表单的问题。

我设置了一个“创建新项目”表单,以显示在项目列表的顶部(当用户单击创建按钮时)

sale_case/show/_requirments_new.html.haml:

- form_for ([@sale_case, @sale_case_requirement]), :html => { :id => 'requirement_form', :class => "submit-with-ajax"} do |f|
...
%button{ :type => "submit" } Save Requirement

application.js:

jQuery(document).ready(function() {
  jQuery(".submit-with-ajax").submitWithAjax();
}
...
jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    jQuery.post(this.action, jQuery(this).serialize(), null, "script");
    return false;
  })
  return this;
};

requirements_controller.rb:

def create
  @sale_case_requirement = @sale_case.requirements.new(params[:requirement])
      if @sale_case_requirement.save
      @message = "Success..."
      @success = true
  #...
  respond_to do |format|
    format.js
  end
end

需求/create.js.erb:

mesg("<%= @message %>");
<%- if @success %>
  jQuery("#requirement_form")[0].reset();
  jQuery('#requirements').load('<%= requirements_view_sale_case_requirements_path(@sale_case.id) %>' );
<% end %>

第一次一切都运行良好,不引人注意。当用户创建第二个项目(在通过 ajax 加载的表单上)时,问题就出现了。 该按钮未绑定(bind)到 SubmitWithAjax 函数。 .load(ing) 内容时如何做到这一点?

为了让它工作,我最终不得不在部分(强制)中执行此操作,但它让我无法弄清楚这一点。 :

%button{ :type => "submit", :onclick => "jQuery.post('#{sale_case_requirements_path(@sale_case.id, @sale_case_requirement.id)}', jQuery('#requirement_form').serialize(), null, 'script'); return false;"} Save Requirement

最佳答案

以下是我根据 Ender 的输入最终对代码进行的更改。我在用他的代码版本查找“submitWithAjax”时出错,但他给我指出了正确的方向,在阅读 .live 文档后,我想出了这个有效的方法:

application.js

jQuery(document).ready(function() {

  # Just put it all in one place
  jQuery(".submit-with-ajax").live('submit', function() {
        jQuery.post(this.action, jQuery(this).serialize(), null, "script");
        return false;
      });
...
}

sale_case/show/_requirments_new.html.haml:

# Change the button back to unobtrusive
%button{ :type => "submit"} Save Requirement    

谢谢!

关于jquery - 如何(重新)绑定(bind)以在 .load(ed) 表单上提交按钮/表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3399252/

相关文章:

jquery:输入标签中的向上/向下箭头键更改所选的 <select> 项目

javascript - 如何在悬停时更改模式弹出窗口的字体大小

javascript - 使复选框变大(网站仅支持 chrome)

ruby-on-rails - Searchkick:无法找到原始记录时删除文档

javascript - 将 jQuery.on(event,selector,func) 转换为 .addEventListener(event, func) 特别是 DOM 树后面的选择器部分和事件气泡

jquery - 在 jquery 更改后将背景颜色设置回原始颜色

ruby-on-rails - 使用 map-reduce 进行视频转换

ruby-on-rails - Time.now.beginning_of_week 给出两个不同的值

ruby-on-rails - i18n-tasks 无法路由键

ruby-on-rails - 在一个 .each 循环中查询多个表