简体   繁体   中英

Rails 3.2.13 Javascript Asset Pipeline

I am working on a Rails 3.2.13 app, and encountering the following problem:

The Javascript files I wrote in the app/assets/javascripts/ directory don't seem to be run.

I have JS code in a file called menu_list.js in the app/assets/javascripts/ directory, but it does not do anything. Whereas when I put the same code on the view page in a tag, it works.

<script>$("#sortable").sortable();</script>

Here's my application.js file:

//= require jquery
//= require jquery_ujs
//= require jquery.purr
//= require jquery-ui
//= require best_in_place
//= require bootstrap
//= require bootstrap-switch
//= require_tree .

my menu_list.js file:

$(function() {
  $("#sortable").sortable();
});

It does not make sense to me, as I thought //= require_tree . would include all the javascript files in the directory. I tried other javascript files too, but they don't seem to have any effects.

造成这种情况的最常见原因是,对默认布局上的javascript_include_tag的调用,然后您创建了另一个布局,忘记在其中添加include,然后在使用该新布局的控制器中没有任何效果。

$("#sortable").sortable();

If this truly is all you have in app/assets/javascripts/menu_list.js it will run as soon as the script is loaded, which is not what you want. You want to run the above code at least after the DOM has fully loaded into the page and not before.

$(function() {
  $("#sortable").sortable();
});

If the environment you're running in is :development , and you properly have the following in your layout

<%= javascript_include_tag "application" %>

you will see a separate <script> tag for every Javascript file Sprockets is loading. The //= require_tree . will pick up your app/assets/javascripts/menu_list.js file.

I suggest also making sure you don't have any precompiled version of your assets in place by running the following in shell

rake assets:clean

You can also force debug mode (individual <script> tags for each file) by adding a :debug option to the above include tag

<%= javascript_include_tag "application", debug: true %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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