如何使.coffee文件在rails中的表单中的复选框上工作?

时间:2013-08-16 17:00:17

标签: ruby-on-rails

  1. 首先,我每次修改.coffee文件后都应该运行“bundle exec rake:precompile”吗?我发现它通常不会自动生效。

  2. 我有一个表单,我想选中复选框以在网页上显示内容。

  3. 我在app\assets\javascripts\testbeds.js.coffee中写了一个文件,内容为:

    alert "ddd"
    
    $(".checkbox1").click ->
      alert "aaa"
    
    $("#manually").click ->
      alert "aaa"
    
    $("#manually").change ->
      alert "aaa"
    
    $('input[type=checkbox]').on 'change', ->
      alert(0)
    

    视图文件:app\views\testbeds\edit.html.erb

    <h1>Editing testbed</h1>
    
    <%= render 'form' %>
    <%= link_to 'Show', @testbed %> |
    <%= link_to 'Back', testbeds_path %>
    

    app\views\testbeds\_form.html.erb的内容只有一个复选框:

    <%= form_for(@testbed) do |f| %>
      <% if @testbed.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(@testbed.errors.count, "error") %> prohibited this testbed from being saved:</h2>
    
          <ul>
          <% @testbed.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
          <% end %>
          </ul>
        </div>
      <% end %>
    
      <div class="field">
        <%= f.label :configuration_id %><br />
        <% selected = (@configuration.nil?) ? nil : @configuration.id %>
        <%= f.select :configuration_id, options_from_collection_for_select(@configurations, 'id', 'name', selected) %>
        <label class="checkbox1">
         <input id="manually" type="checkbox" name="manually" value="manually">
        </label>
    
          <label id="label"> Choose resources manually</label>
      </div>
      <div id="resources">
      </div>
      <div class="actions">
        <%= f.submit %>
      </div>
    <% end %>
    

    当我点击或选中复选框时,alert不起作用。但第一行的alert“ddd”显示正确。

    application.js中的已编译内容如下所示。我不确定“(jQuery);”属于上一个函数或此函数,只需附加它。

      }
    
    })( jQuery );
    (function() {
    
      alert("ddd");
    
      $(".checkbox1").click(function() {
        return alert("aaa");
      });
    
      $("#manually").click(function() {
        return alert("aaa");
      });
    
      $("#manually").change(function() {
        return alert("aaa");
      });
    
      $('input[type=checkbox]').on('change', function() {
        return alert(0);
      });
    
    }).call(this);
    // This is a manifest file that'll be compiled into application.js, which will include all the files
    // listed below.
    

    有人能告诉我原因并告诉我这是如何运作的吗?

    非常感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用on('change')。这是普通jQuery(非咖啡)中的jsfiddle:http://jsfiddle.net/CrQP6/

在咖啡中,它会是

$('input[type=checkbox]').on 'change', ->
  alert(0)

答案 1 :(得分:0)

  1. 不,您不需要在rails开发环境中手动重新编译coffeescript文件,通常

  2. 请务必阅读asset pipeline documentation。这可能是由app / assets / application.js需要testbeds javascript文件引起的。

  3. 更改您的代码只是为了进行警报('测试')以验证您的javascript是否正确加载到资产管道中 - 如果这样做,那么您执行jquery绑定的方式只会出现问题< / p>

  4. 编辑: 可能出现的问题是,一旦您运行rake资产:在本地预编译,它将仅为公共/资产提供资产。如果要返回按需编译行为(这是您想要的),则需要删除该目录