简体   繁体   English

jQuery在Coffeescript函数Rails中不起作用

[英]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. 我试图在Rails中加载特定视图时进行简单的类更改。 Specifically I want to run: 具体来说,我想运行:

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

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: 但最终的javascript最终将我的Jquery命令放在函数之外:

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. 如果只想在加载页面时设置一个类,那么答案取决于您是否正在使用Rails 4中的Turbolinks

With turbolinks, you could just hook into the page:load event like 使用turbolinks,您可以像这样进入page:load事件

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

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

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