jQuery事件替换类 [英] Jquery event of replaced class

查看:131
本文介绍了jQuery事件替换类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery创建隐藏/显示"按钮.单击.cminus时,它需要隐藏.arrowwrap和.commentbody并将其自己的类替换为cplus.然后,如果单击.cplus,则会发生相反的情况.

I'm trying to create a Hide/Show button with jQuery. When .cminus is clicked, it needs to hide .arrowwrap and .commentbody and replace it's own class with cplus. Then if .cplus is clicked opposite needs to happen.

问题1:在下面的示例中,.cminus替换为.cplus之后,.cplus在单击时不会触发点击事件.

Problem 1: In example below after .cminus is replaced with .cplus, the .cplus does not fire click event when it's clicked.

(编辑问题2已移至其他故障单) 问题2:我没有达到.commentbody的权限来隐藏/显示它

(EDIT problem 2 moved to separate ticket) Problem 2: I'm not reaching the .commentbody right to hide/show it

HTML:

<div class="commentline">
    <div class="carrowholder">
        <div class="cminus"></div>
        <div class="arrowwrap">
        </div>
    </div>
    <div class="commentholder">
        <div class="commenttitle">
            Title
        </div>
        <div class="commentbody">
            Body
        </div>
    </div>
</div>

jQuery代码:

$('.cminus').click(function(e) {
  $(this).next('.arrowwrap').hide();
  $(this).parent().next('.commentholder .commentbody').hide();
  $(this).removeClass('cminus');
  $(this).addClass('cplus');
})

$('.cplus').click(function(e) {
  alert("clicked cplus");
  $(this).next('.arrowwrap').show();
  $(this).addClass('cminus');
  $(this).removeClass('cplus');
})

推荐答案

使用.toggleClass('cminus');等,然后使用一个事件处理程序,或者在父元素上使用.on/.live以允许委派事件.

Use .toggleClass('cminus'); etc. and then have one event handler OR use .on/.live on the parent element to allow for delegated events.

$(this).parent().next('.commentholder .commentbody').hide();

我认为.commentholder是多余的,因为您要指定next来获取下一个兄弟.

I think the .commentholder is redundant as you're specifying next which gets the next sibling.

这篇关于jQuery事件替换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆