Jquery Onclick not happening second time

为君一笑 提交于 2019-12-01 20:38:35

It's because the click handlers are only applied to those elements that match at document load. You should use a separate class to identify all of the links, then set up a single click handler that looks at the class that the link has and then does the appropriate class transformation.

$(document).ready(function () {
    $('.clickable').click(function () {
       var $this = $(this);
       if ($this.hasClass('optional')) {
           $this.removeClass('optional').addClass('selected');
       }
       else if ($this.hasClass('selected')) {
            $this.removeClass('selected').addClass('rejected');
       }
       else if ($this.hasClass('rejected')) {
            $this.removeClass('rejected').addClass('optional');
       }
       return false;
    });
});


<div id="tagContainer"> 
    <a href="#" class="clickable rejected">a</a>
    <a href="#" class="clickable optional">b</a>
    <a href="#" class="clickable selected">c</a>
</div>

Not sure if you already know about this or not.... Check the jquery documentation on the .live() functionality. That way, you could do something like this.

$('.optional').live('click', function () {
                $(this).removeClass('optional').addClass('selected');
                return false;
            });

And then you don't have to worry about classes not existing at document load. As the classes change on the elements, they'll automatically be bound to.

You can change your code like this

$(document).on("click", ".clickable", function(){
       var $this = $(this);
       if ($this.hasClass('optional')) {
           $this.removeClass('optional').addClass('selected');
       }
       else if ($this.hasClass('selected')) {
            $this.removeClass('selected').addClass('rejected');
       }
       else if ($this.hasClass('rejected')) {
            $this.removeClass('rejected').addClass('optional');
       }
       return false;    
});

You can also change your click handler to the live click handler:

$(document).ready(function () {
        $('.optional').live('click',function () {
            $(this).removeClass('optional').addClass('selected');               return false;
        });
        $('.selected').live('click',function () {
            $(this).removeClass('selected').addClass('rejected');               return false;
        });
        $('.rejected').live('click',function () {
            $(this).removeClass('rejected').addClass('optional'); 
        });
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!