我按照规范将所有代码都放在$(document).ready中,但是我也应该在代码的结尾处放置我的“ popstate”监听器吗?还是有关系吗?
这并不重要,因为它是一个事件,甚至可以在您的ready方法之前完成。唯一需要放在里面的document ready是与 DOM 交互的代码。其他所有内容都不会(也可能不应该)放入准备好的文档中。
例子:
window.onpopstate = function() {
// binding this event can be done anywhere,
// but shouldn't be inside document ready
};
$(document).ready(function() {
// DOM manipulation and other stuff
});
Run Code Online (Sandbox Code Playgroud)
现在,popstate 实际被触发的时间与绑定时有很大不同。根据 Mozilla 文档:
每次活动历史条目发生更改时,都会将 popstate 事件分派到窗口。如果被激活的历史条目是通过调用history.pushState()创建的,或者是受调用history.replaceState()影响的,则popstate事件的state属性包含历史条目状态对象的副本。