问题描述
除了初始加载之外,Turbolinks会阻止正常的 $(document).ready()
事件在所有页面访问中触发,如上所述和。但是,链接答案中的所有解决方案都不适用于Rails 5。如何像以前的版本一样在每次访问页面上运行代码?而不是听准备好
事件,您需要在每次访问页面时挂钩Turbolinks触发的事件。
不幸的是,Turbolinks 5(这是版本Rails 5中出现的内容已被重写,并且不使用与之前版本的Turbolinks相同的事件名称,导致提到的答案失败。现在有效的是收听事件,如下所示:
$(document).on('turbolinks:load',function(){
console.log(It适用于每次访问!)
})
Turbolinks prevents normal $(document).ready()
events from firing on all page visits besides the initial load, as discussed here and here. None of the solutions in the linked answers work with Rails 5, though. How can I run code on each page visit like in prior versions?
Rather than listen to the ready
event, you need to hook in to an event fired by Turbolinks for every page visit.
Unfortunately, Turbolinks 5 (which is the version that appears in Rails 5) has been re-written, and does not use the same event names as in previous versions of Turbolinks, causing the answers mentioned to fail. What works now is to listen to the turbolinks:load event like so:
$( document ).on('turbolinks:load', function() {
console.log("It works on each visit!")
})
这篇关于Rails 5:如何使用带有turbo-links的$(document).ready()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!