简体   繁体   中英

Manually calling document.ready

Is there a way to force the event document.ready to fire through Javascript? The new Rails 4 default of using turbo links by default kills this event from firing when switching pages. This causes problems with more 'traditional' jQuery code that is wrapped in $(function(){}); .

I've taken a look around and don't see any way of making this event fire through code and most answers on here offer other work-arounds.

So is it even possible to make document.ready fire through regular Javascript code?

Are you using jQuery then? If you are, try an explicit call to Jquery's $.ready(); function at the end of your code. This will force all jQuery "ready" functions to be called, both your own and those in any plugins you're using.

If that doesn't work, you can try $(window).load(); .

If neither of those work and you're using some type of asynchronous call, you probably have some other issue to weed out first. Good luck!

我认为在不对代码进行重大更改的情况下执行此操作的最简单方法是侦听自定义事件而不是 ready 并且在 ready 事件中触发自定义事件。

From the turbolinks documentation : You have to make the document listen to one of the turbolinks custom page events, for example:

$(document).on('page:change', function() {
    // Your code
});

The easiest solution:

Insert your Gemfile this:

gem 'jquery-turbolinks', '~> 1.0.0'

Insert your application.js this:

//= require jquery.turbolinks

(Don't forget a bundle update )

If you have in your coffescript code the following it will be triggered for full page reload or for opening a page via link when turbolinks is active:

$ ->
   alert 'Hello World'

( $ -> means document.ready )

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