问题描述:

I have a Javascript, which uses on ready state in my Rails app.

It should actually react to a link-click, so it's

 <%= javascript_tag "$(document).ready(function(){$('#save').click(save);});"%>

but when rendering the view, by getting there from another view, it does not work. It only works, when I use f5 to reload the site.

Do you know why it is like this?


EDIT:

I have added alert('it works'); to my $(document).ready(function(){}; but it does not work yet. So the document ready event is not being fired.


@BroiSatse: Yes, I have turbolinks installed. Here are my require parts from my application.js:

//= require jquery

//= require jquery.turbolinks

//= require jquery_ujs

//= require turbolinks

//= require_tree .

网友答案:

Try modyfining this to

$(function(){ console.log("ready fired");$.("link"();));

to check if document ready event is being fired

If it's not you will need to find event that does fire and bind functionality to it.

网友答案:

If I understand your problem, would something like this be sufficient. Comment if I'm not understanding the problem.

$(document).ready(funtion(){

    $(document).on('click touchstart', '#save', function(){
        save();
    });

    function save(){
        console.log('This Works');
    }

});
网友答案:

It seems like a typical issue caused by turbolinks gem. This gem improves website performance by not loading the whole page for each request. The obvious problem is that $(document).ready is not triggered when the new page is loaded. To fix it you can change your call to:

  <%= javascript_tag "$(document).on('page:load', function(){$('#save').click(save);});

However the best way I found to deal with it is to install jquery-turbolinks gem as well. Just add

gem 'jquery-turbolinks'

to your gemfile, run bundle install and modify your application.js file to look sth like:

//= require jquery
//= require jquery.turbolinks
// ... 
//= require turbolinks
相关阅读:
Top