简体   繁体   中英

Jquery not working in Coffeescript function Rails

I'm new to coffee script, so forgive me if this is a simple problem.

I'm trying to make a simple class change when a specific view is loaded in Rails. Specifically I want to run:

$(#mydiv).addClass('active')

In my coffee script, I have the following:

class MyApp.Sessions extends MyApp.Base
  constructor:() ->
    super  # call Base class for core functionality
    this   # and be sure to return this

  index:() -> 
    $ -> 
        $('#mydiv').addClass('active')

but the resulting javascript ends up placing my Jquery command outside of the function:

Sessions.prototype.index = function() {
  return $(function() {});
};

$('#mydiv').addClass('active');

Any ideas?

This seems really complicated. If you only want to set a class when a page is loaded, then the answer depends on if you're using Turbolinks from Rails 4.

With turbolinks, you could just hook into the page:load event like

document.on 'page:load', () ->
  $('#mydiv').addClass 'active'

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