如果单击我站点上的任何链接(a),如何运行jQuery函数

我在核心商务系统上有一个新的网站,它没有很多HTML和非PHP的访问权限。 我唯一能用的就是JavaScript。 他们的系统目前在页面加载速度方面不是很好,所以我希望至少客户知道在等待5-8秒加载页面时正在发生的事情。 所以我找到了一些代码并将它们组合在一起,以便在加载页面时显示加载GIF的叠加层。 目前,如果您单击页面上的任何位置,它将运行但我希望它仅在单击站点上的链接(a href)时运行(任何链接)。

我知道你可以做一个在页面加载时运行的代码,但这不够好,因为它执行得太晚(几秒钟后)

无论如何,这是我的网站www.cosmeticsbynature.com,这是我使用的代码。 任何帮助都会很棒。

var ld=(document.all); var ns4=document.layers; var ns6=document.getElementById&&!document.all; var ie4=document.all; if (ns4) ld=document.loading; else if (ns6) ld=document.getElementById("loading").style; else if (ie4) ld=document.all.loading.style; jQuery(document).click(function() { if(ns4){ld.visibility="show";} else if (ns6||ie4) var pb = document.getElementById("loading"); pb.innerHTML = ''; ld.display="block"; });

 //to select all links on a page in jQuery jQuery('a') //and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here) jQuery('a').on('click', function () { //my click code here }); //and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched) jQuery(document).on('click', 'a', function () { //my click code here }); 

注意: .on()是jQuery 1.7中的新增function。

如果在页面中包含jQuery,这样做会更容易。 完成后,您可以:

 $('a').click(function() { // .. your code here .. return true; // return true so that the browser will navigate to the clicked a's href } 

你正在做的是将click处理程序绑定到文档,这样用户将在哪里单击代码将被执行,更改这段代码

 jQuery(document).click(function() 

 jQuery("a").click(function() 
 $("a").click(function(){ //show the busy image }); 

怎么样 – 我假设#loading {display:none}

 

http://jsfiddle.net/vol7ron/wp7yU/

我在大多数答案中看到的一个问题是人们假设点击事件仅来自 (锚)标签。 在我的实践中,我经常将点击事件添加到spanli标签。 给出的答案不考虑这些。

下面的解决方案会嗅探包含两个事件的元素,这些事件是使用jQuery.click(function(){})

 $(document).ready(function(){ // create jQuery event (for test) $('#jqueryevent').click(function(){alert('jqueryevent');}); // loop through all body elements $('body *').each(function(){ // check for HTML created onclick if(this.onclick && this.onclick.toString() != ''){ console.log($(this).text(), this.onclick.toString()); } // jQuery set click events if($(this).data('events')){ for (key in($(this).data('events'))) if (key == 'click') console.log( $(this).text() , $(this).data('events')[key][0].handler.toString()); } }); }); 

使用上面的内容,您可能希望创建一个数组并将元素中的元素推送到每个地方(您看到console.log