是否有可能确保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之前执行。有一个更好的方法吗?而一种真正有效的方法?
您在'$('external-url')'中的选择器不正确,当您应该使用类选择器时,您正在使用属性选择器。我认为这是一个错字。 – nullability
你见过这个答案吗? http://stackoverflow.com/questions/16219822/does-jquery-onclick-always-run-before-a-href-fires –
你也可以寻找类似onbeforeunload的事件。但是,这不会在Safari – Naresh217