简体   繁体   中英

Jquery Doesn't work On Rails

I am having trouble using jquery on rails.In my comments.js file i add

//= 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();
    });                             
})

In my application.html.haml i have;

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

!!!!!!!!!!!!!!!!!UPDATE!!!!!!!!!!!!!!!!!!! It got solved by adding preventDefault.Final version is below:

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

})

This is the same underlying problem you had over in your other question: Can't select link_to tag as jquery selector Rails

You're using turbolinks which does not fire the $(document).ready event on page transition. Copying from the turbolinks docs: 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() { // ... }) 

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