简单的jQuery无法在Rail 3.2中运行

时间:2013-03-15 22:08:43

标签: jquery ruby-on-rails ruby twitter-bootstrap ruby-on-rails-3.2

这个让我现在要走了几个小时。如果我能提供更多信息,请联系我们。

我正在尝试在我的Rails 3.2应用程序中使用一些基本的jQuery。有问题的jQuery是按下按钮提供动作(此刻,只是一个警告对话框,知道它正在工作)。

应用/视图/命令/ index.html.erb

...

<button type="button" class="btn" id="button">My button</button>

...

我已尝试过jQuery / JS代码的许多变体,包括......

应用/资产/ Javascript角/ orders.js

$('#button').click(function() {
    alert("Test message");
});

$(document).ready(function() {
    $('#button').click(function() {
        alert("Test message");
    });
});

$(document).ready(function() {
    $('#button').button();
    $('#button').click(function() {
        $(this).button('loading');
    });
});

需要注意的一些要点:

  • 这是在开发环境
  • 中运行的
  • JS文件显示在源代码和Chrome网络/资源面板中,没有错误。
  • 我尝试重新订购我的application.js文件。
  • 我还不熟悉CoffeeScript,但我愿意尝试基于CoffeeScript的解决方案。
  • Chrome报告了Morris中的错误。

我的 app / assets / javascripts / application.js 供参考

//= require jquery
//= require jquery_ujs
//= require raphael
//= require morris
//= require bootstrap
//= require_tree .

有关追踪此错误的步骤的任何建议都非常有用!


更新

尝试以下CoffeeScript解决方案,但没有运气。

jQuery ->
    jQuery('#button').click ->
        alert("Test msg")

// ... which generates ...

(function() {

  jQuery(function() {
    return jQuery('#jamcake').click(function() {
      return alert("You have cake?");
    });
  });

}).call(this);

尝试将按钮更改为链接,但无济于事。

尝试回归基础,以下工作。

alert("Hello");

但是,以下情况并非......

$(document).ready(function() {
    alert("Hello there");
});

3 个答案:

答案 0 :(得分:2)

在黑暗中拍摄,但其他一个js库可能与jQuery使用$

冲突

尝试:

jQuery(document).ready(function($) {
  // code here, using $ as usual

  $('#button').click(function() {
    alert("Test message");
  });
});

答案 1 :(得分:0)

html的

<button type="button" class="btn" id="first-test">My button</button>

.js

$(function() {
   $("button#first-test").on("click",function() {     
     alert(hi); 
   });            
});

答案 2 :(得分:0)

尝试这个并检查控制台以确保:事件正在触发,jQuery可以找到该元素。

$(document).ready(function() {
    console.log($('#button').size());
});

如果一无所获,可能会发生冲突,或者与其他库的错误导致脚本的其余部分无法运行。