简体   繁体   English

没有在Rails 5中使用Turbolink刷新页面,Javascript就无法运行

[英]Javascript doesn't run without page refresh using turbolinks in Rails 5

I've seen several posts on here, as well as blog posts, about this issue. 我在这里看到了关于此问题的几篇文章以及博客文章。 None of them have helped me so far, eg this one: Same rails and turbolink version 到目前为止,它们都没有对我有所帮助,例如: 相同的rails和turbolink版本

Here's an example of js which doesn't load without refreshing the page: 这是一个不刷新页面就不会加载的js示例:

document.addEventListener('turbolinks:load', function() {
    document.getElementById(id[0]).oninput=function () {
        validate(id[0]);
    }
});

The Javascript runs fine without Turbolinks, and removing Turbolinks is not a solution for me. 没有Turbolinks的情况下,JavaScript可以正常运行,而删除Turbolinks对我来说不是一个解决方案。

Note: It does work if I require a specific JS file from application.html.erb , but then it runs every file on all pages on the web site, and the JS has to be page specific. 注意:如果我需要来自application.html.erb的特定JS文件,它确实可以工作,但随后它将在网站的所有页面上运行每个文件,并且JS必须是特定于页面的。

You should use this one for turbolinks. 您应该将其用于Turbolink。

$(document).on('page:load', ready);

But this is quite bad, because on some pages you want use turbolinks, on other you don't want. 但这是很糟糕的,因为在某些页面上您想要使用涡轮链接,而在其他页面上则不需要。 Soon you will have script initialized just by document ready(because you cannot wait page to load), and other via page:load. 很快,您将仅通过文档就绪(因为无法等待页面加载)以及其他通过page:load初始化脚本。 So better just prevent this 'unexpected behaviour': 因此最好防止这种“意外行为”:

= link_to "Page", some_path(@page), data: { turbolinks: 'false' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM