开发者

How to prevent users from clicking multiple times on a linked image?

I have a page with a linked image, where the link takes a bit of time to load. Therefore, users tend to click multiple times on it. This occasionally causes errors to crop up in the code. How do I prevent users from clicking on the link more than once?

In an attempt to remedy this, I changed the link to an onClick eve开发者_如何学运维nt and then in the function I used the code:

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

However, that doesn't seem to be helping. Also, I'd prefer to keep it a simple linked image instead of using javascript.


Once solution is to add a class to the element that is used as a flag to determine of the code should run.

Here's an example: 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
   }
});

With the added class, you can also change the look of the image (lower its opacity perhaps) to indicate that it shouldn't be clicked again.

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


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


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

if your image is wrapped by a link the code will be

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


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

    evt.preventDefault();
});


A hacky CSS solution that might/might not work: create another image element, without the link and make it a sibling to the link, like this:

<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>

Now apply this CSS:

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

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

This should show the non-link image when the link is clicked (theoretically).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜