简体   繁体   English

添加和删​​除类中jquery Click事件的问题

[英]Problems with jquery Click events in adding and removing classes

I am trying to add and remove class using jquery click function. 我正在尝试使用jquery click函数添加和删除类。 It works for the first click but I don't know why it is not working for the second click. 它适用于第一次点击,但我不知道为什么它不适用于第二次点击。 It not showing any errors as well. 它也没有显示任何错误。

Here is the html 这是HTML

<p class="right hand hidesubcategory">Hide</p>

And the script: 和脚本:

$('.hidesubcategory').click(function() {   
        $(this).text('Show');
        $(this).removeClass('hidesubcategory').addClass('showsubcategory'); 
});

$('.showsubcategory').click(function() {
        $(this).text('Hide');
        $(this).removeClass('showsubcategory').addClass('hidesubcategory');
});

Thanks in advance 提前致谢

At the time of binding, there was no element with class .showsubcategory, hence that binding never takes place. 在绑定时,没有类为.showsubcategory的元素,因此绑定从未发生。

With dynamic elements/bindings you need to update the code like following. 使用动态元素/绑定,您需要像下面这样更新代码。

$(document).on('click', '.hidesubcategory', function() {   
        $(this).text('Show');
        $(this).removeClass('hidesubcategory').addClass('showsubcategory'); 
});

$(document).on('click', '.showsubcategory', function() { 
        $(this).text('Hide');
        $(this).removeClass('showsubcategory').addClass('hidesubcategory');
});

For reference - http://plnkr.co/edit/zCkzsnUmDXqV7cmvtP9g?p=preview 供参考-http://plnkr.co/edit/zCkzsnUmDXqV7cmvtP9g?p=preview

$(function(){
 $(document).on('click', 'p.right.hand', function() {   
        var thisItem = $(this);

        if(thisItem.text() == 'Hide'){
          thisItem.text('Show');
        } else {
          thisItem.text('Hide');
        }

        if(thisItem.hasClass( "hidesubcategory" )){
          thisItem.removeClass('hidesubcategory').addClass('showsubcategory');
        } else {
          thisItem.removeClass('showsubcategory').addClass('hidesubcategory');
        }


});
});

Try this code. 试试这个代码。

$(document).ready(function() {
    $('.hidesubcategory').live("click",function () {
        $(this).text('Show');
        $(this).removeClass('hidesubcategory').addClass('showsubcategory');
    });

    $('.showsubcategory').live("click", function () {
        $(this).text('Hide');
        $(this).removeClass('showsubcategory').addClass('hidesubcategory');
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM