2010-10-08 58 views
4

我有一个链接图像的页面,其中链接需要一些时间来加载。因此,用户往往会多次点击它。偶尔会导致代码中出现错误。如何防止用户多次点击该链接?如何防止用户在链接的图像上多次点击?

在试图解决这个问题,我改变了链接到一个onClick事件,然后在功能我使用的代码:

$('#myImageId').unbind('click'); 
window.location.href = "myLink"; 

然而,这似乎并没有被帮助。此外,我宁愿保留一个简单的链接图像,而不是使用JavaScript。

+0

你将不得不选择javascript或让你的用户满足他们的ocd倾向。你的html是什么样的? – lincolnk 2010-10-08 16:18:52

+0

我想我会选择JavaScript,然后... – dmr 2010-10-08 16:20:21

回答

6

一旦解决方案是将一个类添加到用作一个标志,以确定代码应该运行的元件。

下面是一个例子:http://jsfiddle.net/qLhr8/

$('#myImageId').click(function() { 
    var $th = $(this); 
    if(!$th.hasClass("pending")) { 
      // Add the "pending" class, so subsequent clicks will not 
      // run the code inside this if() 
     $th.addClass("pending"); 
     window.location.href = "myLink"; 
     // you could do a setTimeout to remove the class 
     // if the new page never loads 
    } 
}); 

与添加的类,你还可以改变图像的外观(可能降低其不透明度)以表明它不应该再次点击。

.pending { 
    opacity: .4; 
    filter:alpha(opacity:40); 
    cursor: wait; 
} 
+0

简单和优雅,让他们知道发生了一些事情,有着良好的用户体验。我喜欢。 – 2010-10-08 17:03:47

0

哈克CSS的解决方案,可能/可能无法正常工作:创建另一个图像元素,没有链接,使其成为同级的链接,像这样:

<div> 
    <a href="http://www.long-loading.com" id="link"><img src="my_img.png" id="img_link" alt="GO" /></a> 
    <img src="my_img.png" id="img_nolink" alt="GO" /> 
</div> 

立即应用此CSS:

#img_nolink { display: none; position: relative; top: -200px; /* Height of the image */ } 

#link:active + #img_nolink { display: block; } 

这应该显示单击链接时的非链接图像(理论上)。

1
<img src="..." id="myImageId"> 


$('#myImageId').bind('click', function() { 
    $(this).unbind('click'); 
    /* do long time task.... 
}); 

如果图像是由一根连杆包裹代码将是

<a href="#"><img src="..." id="myImageId"></a> 


$('#myImageId').parent().bind('click', function(evt) { 
    $(this).unbind('click'); 
    /* do long time task.... 

    evt.preventDefault(); 
}); 
相关问题