Allow just one click in class JQUERY

喜你入骨 提交于 2019-12-17 21:16:43

问题


I have a link that will load via ajax some content.

My problem is, I don't want to remove the text "Load comments", I just want to not allow more clicks in this class.

<a href="javascript:;" class="showcomments" id="'.$idf.'">Load comments</a>

Jquery

var Progressajax = false;
$(function() {
     $(".showcomments").click(function(){

               if(Progressajax) return;
                   Progressajax = true;

    var element = $(this);
    var id = element.attr("id");

    Progressajax = false;
           alert("ok");
           $(data).hide().prependTo('.varload'+id).fadeIn(1000);
         //$(element).remove();
        $(element).removeAttr("href");
        $(element).removeClass('showcomments');
    }); 
    });

I just want to see OK the first time. How can I remove this class?

$(element).removeClass('showcomments');

This is not working...

http://jsfiddle.net/qsn1tuk1/


回答1:


Use jQuery's one() function

$(".showcomments").one("click", function() {

http://www.w3schools.com/jquery/event_one.asp

The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs.

When using the one() method, the event handler function is only run ONCE for each element.




回答2:


When you bind an event handler, you bind to the element, not to the class. Removing a class from an element doesn't change which event handlers are bound to the element.

You could use off() to remove the event handler:

$(this).off('click');

http://jsfiddle.net/om6ggvyu/



来源:https://stackoverflow.com/questions/32616022/allow-just-one-click-in-class-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!