Javascript 事件阻止默认不工作
当删除Javascript 事件阻止默认不工作,javascript,jquery,html,Javascript,Jquery,Html,当删除e.preventDefault()时,哈希标记将出现在likelocalhost/page1.html#之后,但当添加e.preventDefault()时,e.originalEvent.state将显示为null $(function(){ $('.button').click(function(e){ e.preventDefault(); history.pushState({url: 'index.html'},'','page1.h
e.preventDefault()
时,哈希标记将出现在likelocalhost/page1.html#
之后,但当添加e.preventDefault()
时,e.originalEvent.state
将显示为null
$(function(){
$('.button').click(function(e){
e.preventDefault();
history.pushState({url: 'index.html'},'','page1.html');
});
});
$(window).bind('popstate', function(e){
console.log(e.originalEvent);
});
有什么问题?我如何解决它
编辑:
按下按钮时,地址栏会更新(这很好)。但是,当我点击后退按钮时,state对象显示为null(它假设显示{url:'index.html'})您看到的不是bug,而是预期的行为 第一次加载页面时,状态为
/
,状态对象为null。当您使用preventDefault
单击锚定标记时,状态将更改为/page1.html
,并提供一个要存储的对象。现在,当您按下back按钮时,popstate事件发生在状态变回/
之后,该状态没有状态对象
要演示,请单击链接3-4次。现在,每次你回击,originalEvent.state
都会有一个对象,直到你回到/
,当然它没有状态对象
要使默认状态具有状态对象而不是null,请使用replaceState
<a href="#" class="button">Click me</a>
所以,您真正想说的是,event.preventDefault()正在工作,只是当您使用它时,它会对您的popstate事件产生负面影响。使用此代码,您实际上想做什么?我无法重现您的问题。它不是空的@KevinB是的,它说PopStateEvent{state:null,…。在Google Chrome控制台中(或者,也许幸运的是),我在Google Chrome中看到了一个对象。
$(function(){
$('a').click(function(e){
e.preventDefault();
history.pushState({url: 'index.html'},'','page1.html');
});
});
$(window).bind('popstate', function(e){
console.log(e.originalEvent);
});
// give the current state a state object
history.replaceState({url: 'index.html'},'','');