如何建立链接做一些jquery然后去目的地

我在页面中有一个链接,在进入目标页面之前我需要做一些jquery。 我确定有很多方法可以做到这一点,最值得推荐的是什么?

$('#link').click(function(){ alert('you clicked'); }); 
  Google 

显然失败了。 想法?

 $('#link').click(function(e){ e.preventDefault(); alert('you clicked'); window.location.href = $(this).attr('href'); }); 

做任何你想做的事后设置位置。

要更改url,不需要jquery

  document.getElementById('link').href = 'new url here' 

但是,如果您想首先执行某些操作,则需要阻止默认操作

 $('#link').click(function(e){ e.preventDefault(): // do what ever you need here window.location.href = 'new url here'; }); 

这应该工作。

 $('#link').click(function(e){ e.preventDefault(); // this stops the url from being loaded // do whatever js you want to here alert('you clicked'); // then send the user on their way window.location.href = $(this).attr('href'); }); 

请执行下列操作:

  • 使用event.preventDefault禁用默认行为。
  • 做你想做的事。
  • 重定向。

像这样的东西:

 $('#link').on('click', function(event) { event.preventDefault(); // Do something // ... var url = $(this).attr('href'); location.location.href = url; });