2016-07-19 57 views
0

我在使用上rails.In我comments.js jQuery的麻煩文件I加jQuery的不工作on Rails的

//= require jquery 
//= require jquery_ujs 
//= require cocoon 
//= require bootstrap-sprockets 
//= require turbolinks 
//= require_tree . 

$(document).ready(function() { 
    alert("This javascripts thing is reals making me mad!"); 
}); 
$(document).ready(function(){ 
    $("#comments_link").click(function(){ 
     $(".comments-section").toggle(); 
    });        
}) 

在我application.html.haml我有;

= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true 
    = javascript_include_tag 'application', 'data-turbolinks-track' => true 
    = csrf_meta_tags 

!!!!!!!!!!!!!!!!! UPDATE !!!!!!!!!!!!!!!!!!! 它得到了通過添加preventDefault.Final版本解決了下面是:

$(document).ready(function(){ 
$(".harun").click(function(e){ 
    e.preventDefault(); 
    $("section").toggle(); 
});        

})

+0

不應該使用'$(文件)。在( 「準備好了」 ......'但是不贊成http://api.jquery.com/ready/對此表示懷疑。將解決錯誤,但嘗試將內部代碼移動到'alert()'之後並將其刪除 – charlietfl

+0

我嘗試了正常的$(document).ready方式。它也不能正常工作。我應該將其更改爲normal.Thanks –

+0

顯示的jQuery代碼在語法上是正確的在瀏覽器中生成的代碼看起來像什麼 – charlietfl

回答

0

這是你在你的其他問題有過同樣的基本問題:Can't select link_to tag as jquery selector Rails

您使用turbolinks在頁面轉換時不會觸發$(document).ready事件。從turbolinks文檔複製:Running JavaScript When a Page Loads

You may be used to installing JavaScript behavior in response to the window.onload , DOMContentLoaded , or jQuery ready events. With Turbolinks, these events will fire only in response to the initial page load—not after any subsequent page changes.

In many cases, you can simply adjust your code to listen for the turbolinks:load event, which fires once on the initial page load and again after every Turbolinks visit.

document.addEventListener("turbolinks:load", function() { 
    // ... 
})