是否可以确保 jQuery on click 事件在用户转发到外部 URL 之前执行?我已经在谷歌上搜索了两个小时,并在 stackoverflow 上阅读了几篇文章。我就是无法让它发挥作用。
这是我尝试过的:
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);
}
但看起来“if (myCustomEvent()) {”行是在 myCustomEvent 函数返回 true 之前执行的。有一个更好的方法吗?以及一种真正有效的方法?
最佳答案
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);
}
根据您的实际需求,还有其他方法可以处理此问题。
关于javascript - 确保 jQuery on click 在 href 触发之前运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32957712/