2015-10-05 59 views
1

是否有可能确保jQuery on click事件在用户被转发到外部URL之前执行?我一直在使用google搜索2个小时,并在stackoverflow上阅读了一些帖子。我只是无法得到这个工作。确保jQuery在点击之前运行href射击前

这是我已经试过:

HTML:

<a href="http://www.example.com/" class="external-url">Click me</a> 

JS:

$('.external-url').on("click", function (e) { 
    e.preventDefault(); 

    if (myCustomEvent()) { 
     window.location = this.href; 
    } 
}); 

function myCustomEvent() 
{ 
    setTimeout(function() { 
     console.log('Execute some custom JS here before a href firing...'); 
     return true; 
    }, 3000); 
} 

但好像行 “如果(myCustomEvent()){” 是在myCustomEvent函数能够返回true之前执行。有一个更好的方法吗?而一种真正有效的方法?

+0

您在'$('external-url')'中的选择器不正确,当您应该使用类选择器时,您正在使用属性选择器。我认为这是一个错字。 – nullability

+0

你见过这个答案吗? http://stackoverflow.com/questions/16219822/does-jquery-onclick-always-run-before-a-href-fires –

+0

你也可以寻找类似onbeforeunload的事件。但是,这不会在Safari – Naresh217

回答

3

jQuery点击事件确实在位置更改之前运行 - 但是您在点击处理程序中间做了一些异步操作。最容易做的事情是在你想有发生成什么myCustomEvent传递,大致为:

$('external-url').on("click", function (e) { 
    var url = this.href; 

    e.preventDefault(); 

    myCustomEvent(function() { 
    window.location = url; 
    }); 
}); 

function myCustomEvent(fn) { 
    setTimeout(function() { 
    console.log('Execute some custom JS here before a href firing...'); 
    fn(); 
    }, 3000); 
} 

还有其他的方法来处理这取决于你的实际需求。

+0

工作哇!这个伎俩,很好用!非常感谢! – user1878980

相关问题