在链接点击和setTimeout [英] Upon Link Click and setTimeout

查看:98
本文介绍了在链接点击和setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我试图在单击链接后2秒执行一个函数,并等到函数完成执行后再转到链接目标。

In JavaScript, I am trying to execute a function 2 seconds after a link is clicked, and wait until the function completes its execution before going to the link destination.

/* JavaScript */
function myFunction() { /* Block of code, with no 'return false'. */ }

<!-- HTML -->
<a onclick="setTimeout(myFunction, 2000);" href="http://www.siku-siku.com">Link</a>

问题是点击后,浏览器立即转到链接目的地,即 myFunction 没有时间执行。我在这里错过了什么吗?

The problem is upon click, the browser immediately goes to the link destination i.e. myFunction didn't have time to execute. Did I miss anything here?

事先谢谢。

推荐答案

你将需要从您的onclick事件返回false ,以取消实际浏览器处理的页面加载。

You will need to return false from your onclick event, to cancel the actual browser handled page load.

并且从那以后想要关注链接(一旦功能完成),你需要通过javascript来做到这一点。但是你正在使用超时,所以你放弃了对被点击元素的引用,所以我们也需要在方法中传递它(如果你想要这个逻辑用于多个链接

And since you want to follow the link (once the function is complete) you will need to do that through javascript. But you are using a timeout so you loose the reference to the clicked element, so we need to pass that too in the method (if you want this logic for multiple links)

html

<a onclick="return createTimedLink(this, myFunction, 2000);" href="http://www.siku-siku.com">Link</a>

javascript

function createTimedLink(element, callback, timeout){
  setTimeout( function(){callback(element);}, timeout);
  return false;
}

function myFunction(element) { 
/* Block of code, with no 'return false'. */
  window.location = element.href;
 }

演示 http://jsfiddle.net/gaby/mdkjX/2/

这篇关于在链接点击和setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆