简体   繁体   English

Rails中只有document.ready代码在页面重新加载上运行

[英]Only document.ready code runs on page reload in Rails

I'm using this tutorial to load page specific JavaScript in my Rails app. 我正在使用本教程在Rails应用程序中加载页面特定的JavaScript。 My file structure looks like this: 我的文件结构如下所示:

app/assets/javascripts/
├── application.js
├── charts.coffee
├── dashboard
│   └── settings.js
├── dashboard-bundle.js
└── static_pages.coffee

I precompile my assets with config.assets.precompile += %w( *-bundle.js ) and the file dashboard-bundle.js simply includes the line //= require_tree ./dashboard/ . 我使用config.assets.precompile += %w( *-bundle.js )预编译我的资产,文件dashboard-bundle.js仅包含//= require_tree ./dashboard/ Then, on my page where I want to JavaScript to be loaded, I include the JavaScript with = javascript_include_tag 'dashboard-bundle' . 然后,在要加载JavaScript的页面上,将JavaScript包含= javascript_include_tag 'dashboard-bundle'

Here's a sample of what part of my settings.js file looks like: 这是我的settings.js文件的哪个部分的示例:

$(document).ready(function(){
  alert('Page and Javascript loaded!');
});
$('#renderChart1').click(function() {
  alert('You want to edit options for chart1!');
});

When I first load the page from another page, both alerts appear at the appropriate time; 当我第一次从另一个页面加载页面时,两个警报都在适当的时间出现; the first on page load and the second when I click the #renderChart1 button. 第一个是页面加载,第二个是当我单击#renderChart1按钮时。

However, when I reload the page without going to another page first, only the first alert works correctly. 但是,当我重新加载页面而不先进入另一个页面时,只有第一个警报可以正常工作。 When clicking on the button, the alert does not appear. 单击按钮时,不会出现警报。

I've already tried installing jQuery Turbolinks but that did not solve the problem. 我已经尝试安装jQuery Turbolinks,但这并不能解决问题。

I think #renderChart1 was added to DOM after binding .click() method for it, and you should move to document.ready to make sure that element was loaded into DOM, like this: 我认为#renderChart1是在为它绑定.click()方法后添加到DOM的,您应该移至document.ready以确保将该元素加载到DOM中,如下所示:

$(document).ready(function(){
  alert('Page and Javascript loaded!');
  $('#renderChart1').click(function() {
    alert('You want to edit options for chart1!');
  });
});

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

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