在页面加载时触发jQuery一次

时间:2012-08-15 18:02:28

标签: javascript jquery ruby-on-rails-3 coffeescript

更新2012年8月18日:我有什么方法可以让以下问题更容易回答?

我在js.coffee文件中有以下代码,它适用于添加内联到表单。我希望它在加载时自动添加第一行,但不知道如何让它去做...

$('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.preventDefault()

(如果这看起来很熟悉,则从Ryan Bates' Railscast #196 revised)逐字逐句窃取

更新:我尝试了@ Baldrick的建议,但仍然没有骰子:

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.preventDefault()

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

更新2:这里有更多信息:

我的HTML(重要部分):

<div class="modal-body ">
<%= @company.haves.new.warehouse_transactions.new %>
<%= form_for @company do |f| %>

  <div class="form-inline receive-form">
    <h4>Part Details:</h4>
  <%= f.fields_for :haves do |builder| %>
      <%#= render 'have_fields', f: builder %>
    <% end %>
  <%= link_to_add_fields "+", f, :haves, :warehouse_transactions %>
  </div>
</div>

have_fields:

<fieldset>
<%= f.text_field :product_title, :class => 'input-small text_field', :placeholder => "Product Title" %>
<%= f.fields_for :warehouse_transactions do |builder| %>
<%= render 'wht_fields', :f => builder %>
<% end %>
<%= f.hidden_field :_destroy %>
<%= link_to "-", '#', class: "remove_fields" %>
</fieldset>

wht_fields:

<fielset>
  <%= f.number_field :quantity, :class => 'input-small number_field', :placeholder => "Quantity" %>
  <%= f.text_field :cost, :class => 'input-small text_field', :placeholder => "Cost" %>
  <%= f.text_field :location, :class => 'input-small text_field', :placeholder => "Location" %>
  <%= f.text_field :batch, :class => 'input-small text_field', :placeholder => "Batch" %>
  <%= f.select :condition, ['Condition'] + WarehouseTransaction::CONDITIONS %>
  <%= f.hidden_field :_destroy %>
  <%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>

这里也是与link_to_add_fields相关联的rails助手:

  def link_to_add_fields(name, f, association, child_association = nil)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    new_object.send(child_association).new if child_association
    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

我本来希望避免把这个问题变成一本小说,但它就是......我希望有足够的信息来使这个东西发挥作用。

1 个答案:

答案 0 :(得分:0)

下载代码将在加载页面时执行:

$(document).ready(function () {
  // put here code to execute on page loading
});

如果代码只能在一个页面上执行,请将其放在仅由此页面调用的javascript文件中,或者在方法中添加测试以仅在需要时执行代码。