Sol*_*orp 4 javascript javascript-events
我正在使用jquery ajax实现分页,但是操纵了浏览器的历史记录..到目前为止还可以,但是我几个小时前才意识到,如果页面的任何部分都有链接
<a href="#">My link</a>
Run Code Online (Sandbox Code Playgroud)
并单击此链接,将调用函数window.onpopstate,但我不知道为什么,这会在我网站的所有A HREF中发生。
这是我的功能,检测当前状态以调用特定功能,并按国家/地区或搜索字词或指定的url参数加载数据。
window.onpopstate = function(event) {
console.log(event);
var section = $('#wrapper section').attr('id');
if(event && event.state) {
//State for Reviews pagination ?page=x
if (event.state.type == 'pagination') {
popStateShopPage(event.state);
}
//State for Reviews pagination by country ?country=MX&page=x
if (event.state.type == 'country') {
popStateShopPageCountry(event.state);
}
//State for Reviews pagination by search ?search=hello&page=x
if (event.state.type == 'search') {
popStateShopPageSearch(event.state);
}
} else {
if (section == 'shop-page') {
popStateShopPage(1);
}
history.pushState(null);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用这些功能来推动状态
history.pushState({type: 'pagination', page: number_page}, "", "?page="+number_page);
history.pushState({type: 'country', page: number_page, country: country}, "", "?country="+country+"&page="+number_page);
history.pushState({type: 'search', page: number_page, term: term}, "", "?search="+term+"&page="+number_page);
Run Code Online (Sandbox Code Playgroud)
1.当活动历史记录条目更改时,将触发popstate事件。如果要激活的历史记录条目是通过调用history.pushState()创建的,或者受到了对history.replaceState()的调用的影响,则popstate事件的state属性包含历史记录条目的state对象的副本。
2.请注意,仅调用history.pushState()或history.replaceState()不会触发popstate事件。仅通过执行浏览器操作(例如单击“后退”按钮(或在JavaScript中调用history.back()))来触发popstate事件。
之所以触发window.onpopstate是因为,首先,当您单击锚标记时,历史记录已更改;其次,您正在执行浏览器操作。
我认为无法避免这种情况,正如JavaScritp The Definitive Guide中所述:
某些事件会导致Web浏览器执行关联的默认操作。例如,当标签上发生点击事件时,浏览器的默认操作是跟随超链接。仅在事件传播的所有三个阶段都完成之后才执行此类默认操作,并且在事件传播期间调用的任何处理程序都有机会通过调用Event对象的preventDefault()方法来防止发生默认操作。
这三个阶段是:捕获,定位和冒泡。
希望它有用!
| 归档时间: |
|
| 查看次数: |
2114 次 |
| 最近记录: |