是否可以确保在用户被转发到外部URL之前执行单击事件上的jQuery?我已经在谷歌上搜索了2个小时,并在这里阅读了几篇关于堆栈溢出的文章。我就是不能让这件事起作用。
这就是我尝试过的:
HTML:
<a href="http://www.example.com/" class="external-url">Click me</a>联署材料:
$('.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函数能够返回true之前,行"if (myCustomEvent()) {“似乎被删除了。有更好的方法吗?还有一种实际可行的方法?
发布于 2015-10-05 21:03:56
jQuery单击事件确实在位置更改之前运行--但是您正在单击处理程序的中间执行一些异步操作。
最简单的方法是将您想要发生的事情传递到myCustomEvent中,大致如下:
$('.external-url').on('click', function (e) {
const url = this.href
e.preventDefault()
myCustomEvent(function() {
window.location = url
});
});
function myCustomEvent(fn) {
setTimeout(function() {
console.log('Execute custom JS before firing navigation...');
fn();
}, 3000);
}根据您的实际需求,还有其他处理此问题的方法。
https://stackoverflow.com/questions/32957712
复制相似问题