最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prevent click jump on jQuery one() function - Stack Overflow

programmeradmin0浏览0评论

I'm using the one() function in jQuery to prevent multiple clicks. However, when they click the element a second time, it does the annoying click jump and sends you back to the top of the page.

Is there a way to prevent this from happening? Unbinding the click and re-binding it when the function is done has the same result (and I'm assuming that one() just unbinds the event anyways).

A quick example of this happening: /

I'm using the one() function in jQuery to prevent multiple clicks. However, when they click the element a second time, it does the annoying click jump and sends you back to the top of the page.

Is there a way to prevent this from happening? Unbinding the click and re-binding it when the function is done has the same result (and I'm assuming that one() just unbinds the event anyways).

A quick example of this happening: http://jsfiddle/iwasrobbed/FtbZa/

Share Improve this question asked Mar 2, 2011 at 22:54 iwasrobbediwasrobbed 46.7k21 gold badges152 silver badges195 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

I'm not sure if this is better or not, but you could bind a simple function that maintains the return false.

jQuery provides a shortcut for this with .bind('click',false).

$('.someLink').one('click', function() {
    $(this).bind('click',false);
    return false;
});

or if you have several of these links, a very efficient alternative would be to use the delegate()[docs] method to bind a handler to a mon ancestor that takes care of the return false; for you.

Here I just used the body, but you could use a nearer ancestor.

$('.someLink').one('click', function() {
});

$('body').delegate('.someLink','click',function(){return false;});

Try changing the href so the '#' isn't being used: http://jsfiddle/FtbZa/1/

$('.someLink').one('click', function() {
    alert('test');
    return false;
}).attr('href', 'javascript:void(0);');

You could use the standard .click() function and a little logic:

1. $('.someLink').click(function(event) {
2.     event.preventDefault();
3.     if (!$(this).hasClass("clicked"))
4.         alert('This will be displayed only once.');
5.         $(this).addClass("clicked");
   });
  1. Listen to anything with the class someLink for a .click()
  2. Stop the browser doing what it would normally do.
  3. Check if the object has the class clicked (Note this could be any name you wanted)
  4. It hasn't so do something.
  5. Add the class clicked so next time its clicked, it will ignore your code.

See the demo here

The problem is that after the listener has been unbound there is nothing stopping the browser from honoring the link (Which it is treating as an anchor tag) and trying to go to it. (Which in this case will simply lead to the top of the page.

发布评论

评论列表(0)

  1. 暂无评论