rails web app页面之间的跳转的时候使用ducument.ready只有在再次加载的时候才生效, 因为rails用了turbolinks,
https://github.com/turbolinks/turbolinks/blob/master/README.md#running-javascript-when-a-page-loads
Running JavaScript When a Page Loads
You may be used to installing JavaScript behavior in response to the window.onload
, DOMContentLoaded
, or jQuery ready
events. With Turbolinks, these events will fire only in response to the initial page load—not after any subsequent page changes.
In many cases, you can simply adjust your code to listen for the turbolinks:load
event, which fires once on the initial page load and again after every Turbolinks visit.
document.addEventListener("turbolinks:load", function() { // ... })
When possible, avoid using the turbolinks:load
event to add event listeners directly to elements on the page body. Instead, consider using event delegation to register event listeners once on document
or window
.
$(document).ready
依赖于DOMContentLoaded
事件- Turbolinks 接管页面后换页不会产生
DOMContentLoaded
,所以换页之后$(document).ready
无效 - Turbolinks 提供了
page:change
取代$(document).ready
- 现在第一次加载也会触发
page:change
了,所以page:change
可以替代$(document).ready
要注意 turbolinks 会缓存访问过的页面,缓存 restore 的时候也会触发 page:chang
,这样的代码在用户后退的时候会重复绑定:
$(document).on ‘page:change‘, -> $(‘body‘).on ‘click‘, -> console.log(‘hit‘)
page:change
和 $().ready
逻辑一样,区别是 turbolinks restore 的时候页面带着之前的状态,而传统页面后退的时候是干净的。
如果要用 turbolinks,最好就用 page:change
,并且要写可以反复执行不冲突的代码。
现在用 page:change
很少,换成这样写:
$(document).on ‘click‘, ‘body‘, -> console.log(‘hit‘)
还有个 page:load
,考虑到 restore 的问题,page:load
才是对应 $().ready
document.addEventListener("turbolinks:load", function() { if ($(‘#component_component_type‘).attr("data-value") == "display_item") { $(‘.display-item-select‘).show(); $(‘.grid-select‘).hide(); } else if($(‘#component_component_type‘).attr("data-value") == "grid") { $(‘.grid-select‘).show(); $(‘.display-item-select‘).hide(); } else { $(‘.grid-select‘).hide(); $(‘.display-item-select‘).hide(); } }) $(document).on(‘change‘, ‘#component_component_type_id‘, function(e) { if ($(‘#component_component_type_id‘).find("option:selected").text() == "display_item") { $(‘.display-item-select‘).show(); $(‘.grid-select‘).hide(); } else if($(‘#component_component_type_id‘).find("option:selected").text() == "grid") { $(‘.grid-select‘).show(); $(‘.display-item-select‘).hide(); } else { $(‘.grid-select‘).hide(); $(‘.display-item-select‘).hide(); } });