简体   繁体   English

用Javascript编写咖啡

[英]Javascript into Coffee

I struggle with some javascript code in rails. 我在Rails中遇到了一些JavaScript代码。 I use this code to make two drop down menus dynamically. 我使用此代码动态创建两个下拉菜单。 I need to "translate" the code into js.coffee, but I have no clue how to do that. 我需要将代码“翻译”成js.coffee,但是我不知道如何做到这一点。

This is my javascript code: 这是我的JavaScript代码:

    <script>
$(document).ready(function() {
        $('#categories_select').change(function() {
          $.ajax({
            url: "<%= update_subcategories_path %>",
            data: {
              category_id : $('#categories_select').val()
            },
            dataType: "script"
          });
        });
      });
</script>

I tried it with this one, but it does not work: 我用这个尝试过,但是不起作用:

$ ->
  $(document).on 'change', '#categories_select', (evt) ->
    $.ajax 'update_subcategories',
      type: 'GET'
      dataType: 'script'
      data: {
        country_id: $("#categories_select option:selected").val()
      }
      error: (jqXHR, textStatus, errorThrown) ->
        console.log("AJAX Error: #{textStatus}")
      success: (data, textStatus, jqXHR) ->
        console.log("Dynamic category select OK!")

And this is my form: 这是我的表格:

    <%= form_for(@search) do |f| %>
<%= f.collection_select :category_id,  @categories,  :id, :name, {:prompt   => "Select category"}, {:id => 'categories_select'} %>
<%= f.collection_select :subcategory_id, @subcategories, :id, :name, {:prompt   => "Select subcategory"}, {:id => 'subcategories_select'} %>  

With the script it's working fine but I would like to get this javascript out of my html file. 使用脚本可以正常工作,但我想从我的html文件中获取此javascript。 Can anyone help me with this? 谁能帮我这个?

Thank you for any help! 感谢您的任何帮助!

For what it's worth, I think it looks as if you have tried to convert your code to CoffeeScript and change it at the same time. 对于它的价值,我认为您似乎已尝试将代码转换为CoffeeScript 并同时进行更改。 You should probably do the first one first, check that it works, and then the second one. 您可能应该先做第一个,然后检查它是否起作用,然后再做第二个。

This compiles for me, and to the same javascript as yours above. 这会为我编译,并且与您上面的JavaScript相同。 Does it work for you? 对你起作用吗? If so, move on from there: 如果是这样,请从那里继续:

$(document).ready ->
  $('#categories_select').change ->
      $.ajax
        url: "<%= update_subcategories_path %>",
        data: 
          category_id : $('#categories_select').val()
        dataType: "script"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM